Mathematica Understanding the Code: How to Extract Data from a Plot in Mathematica

  • Thread starter Thread starter Swamp Thing
  • Start date Start date
  • Tags Tags
    Data Plot
AI Thread Summary
The discussion focuses on extracting data from a Plot in Mathematica using the Cases function. The provided code snippet utilizes pattern matching to identify and extract the coordinates from a Line object within the plot. The last two arguments in the Cases function, while seemingly irrelevant, are used to specify the level of the expression being searched. The InputForm of the plot reveals the structure of the data, showing how the Line contains numerous x,y coordinates. Understanding this code involves recognizing how pattern matching and substitution work to isolate the desired data points.
Swamp Thing
Insights Author
Messages
1,028
Reaction score
764
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?
 
Physics news on Phys.org
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

Similar threads

Replies
4
Views
1K
Replies
1
Views
2K
Replies
6
Views
4K
Replies
2
Views
3K
Replies
2
Views
1K
Replies
12
Views
3K
Replies
1
Views
2K
Back
Top