Extracting data from a Plot

  • Mathematica
  • Thread starter Swamp Thing
  • Start date
  • #1
An answer posted here...
https://mathematica.stackexchange.com/questions/19859/plot-extract-data-to-a-file
... says you can extract the data from a Plot by doing this:
Code:
data = Cases[Plot[Sin@x, {x, 0, 2 Pi}], Line[data_] :> data, -4, 1][[1]];

Having looked at the doc page on Cases, I can't figure out how this works. (And I can't imagine how someone would come up with this, using only the documentation).

I find that changing the last two arguments (-4 and 1) doesn't affect the result, as long as the third one is negative.

So what is going on in that code?
 

Answers and Replies

  • #2
Bill Simpson
1,071
31
To try to imagine how someone would come up with this, look at

InputForm[Plot[Sin@x,{x,0,2Pi}]]

InputForm presents the data it is given into a less "pretty printed" version that you can look at and use.

When you look at that you should see there are some bits adjusting the appearance and then there is a Line with a vast number of x,y coordinates. And that is followed by more bits adjusting the appearance.

Cases takes an expression and tries to find a matching pattern in it. So in this case it is looking for that Line[...]

Next the :> is doing a substitution. Really all that is doing is stripping off the Line that is wrapped around the points.

And then the last two numbers look like they are choosing the levelspec and the number of patterns to match.

If you try to compare this description to what you see from the InputForm you can see it is trying to control the extraction of the data points that would default to be turned your graph on the screen.

Does this give you an idea how to think about that code?
 
  • Informative
Likes Swamp Thing

Suggested for: Extracting data from a Plot

  • Last Post
Replies
2
Views
369
Replies
1
Views
185
  • Last Post
Replies
2
Views
216
Replies
0
Views
151
Replies
4
Views
501
  • Last Post
Replies
1
Views
419
Replies
2
Views
1K
  • Last Post
Replies
9
Views
3K
  • Last Post
Replies
7
Views
580
  • Last Post
Replies
8
Views
318
Top