# Plot, extract data to a file

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?

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][];


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}] 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}]

• 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
• What are exactly these values Line[data_] :> data, -4, 1][]; that are shown in mathematica??i have to extract values from a plot of a pretty complicated function and these informations are very important to me..thanks in advance! – user30749 Jul 13 '15 at 13:22
• @stathis I am not sure I understand. Are you asking about that adaptive sampling that Mathematica uses? You can see the points used by adding the option Mesh -> All to Plot. – Mr.Wizard Jul 14 '15 at 1:39