Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I need to save data that Mathematica uses inside the Plot command. The format that I would like to have is:

x1 y1
x2 y2
.....

i.e. basically, two columns, x and y (sorted, if possible) so that I can use the data for other programs.

I already played with Export and got the data enclosed in {} and tons of other information I don't need: color, axis, etc.

What is the nicest way to do what I am trying to do?

share|improve this question

1 Answer 1

up vote 14 down vote accepted

First you need to get the data from your Plot. Two methods are extraction with patterns:

data = Cases[Plot[Sin@x, {x, 0, 2 Pi}], Line[data_] :> data, -4, 1][[1]];

and EvaluationMonitor:

data =
 Reap[
   Plot[Sin@x, {x, 0, 2 Pi}, EvaluationMonitor :> Sow[{x, Sin@x}]]
 ][[2, 1]];

I prefer the first method's brevity and the fact that it can be used on existing Graphics output by Plot.

Then you just need to Export the data in the right format:

Export["file.txt", data, "Table"]

A somewhat more interesting example is saving data from a multi-line plot:

gr = Plot[{Sin@x, Cos@x, Sinc@x}, {x, 0, 2 Pi}]

Mathematica graphics

The expression assigned to gr is a Graphics object which has the form:

Graphics[primitives, options]

We are interested in the data that makes up the primitives, therefore we will operate on First @ gr. We will also not restrict the Cases to find only the first match as was done above (the fourth argument of Cases).

multidat = Cases[First @ gr, Line[data_] :> data, -4];

We could then export each part to a separate file like this:

Export["file" <> IntegerString[#2] <> ".txt", #, "Table"] & ~MapIndexed~ multidat
{"file1.txt", "file2.txt", "file3.txt"}

It should be pointed out that if you do not require the adaptive sampling of Plot you can generate your data more simply and directly using Table, e.g.:

Table[{x, Sin@x}, {x, 0, 2 Pi, 0.01}]
share|improve this answer
    
thnx a lot for yr help!:) –  molkee Feb 22 '13 at 0:52
    
I had the same issue with NDSolve graph and I was looking for just 2 colums of pure numbers. This helped a lot. Thanks. –  Cagatay Ozmen Mar 24 '13 at 13:01
    
I understand the use of levelspec -4, but puzzlingly, in the example the pattern allows this to work too: Cases[First@gr, Line[data_] :> data, -1] –  Chris Degnen Mar 25 '13 at 10:47
    
@Chris Don't be puzzled. I normally use -1 with such patterns, but recently I've been trying to be more specific with my level specifications which in some cases makes a significant difference in speed as fewer expressions are scanned wastefully. In this case it doesn't make a big difference. –  Mr.Wizard Mar 25 '13 at 15:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.