Retrieve XY data from matplotlib figure

brettb picture brettb · Nov 21, 2013 · Viewed 51.8k times · Source

I'm writing a little app in wxPython which has a matplotlib figure (using the wxagg backend) panel. I'd like to add the ability for the user to export X,Y data of what is currently plotted in the figure to a text file. Is there a non-invasive way to do this? I've searched quite a bit and can't seem to find anything, though I feel like it is incredibly simple and right in front of my face.

I could definitely get the data and store it somewhere when it is plotted, and use that - but that would be fairly invasive, into the lower levels of my code. It would be so much easier, and universal, if I could do something as easy as:

x = FigurePanel.axes.GetXData()
y = FigurePanel.axes.GetYData()

Hopefully that makes some sense :)

Thanks so much! Any help is greatly appreciated!

edit: to clarify, what I'd like to know how to do is get the X,Y data. Writing to the text file after that is trivial ;)

Answer

Bas Swinckels picture Bas Swinckels · Nov 21, 2013

This works:

In [1]: import matplotlib.pyplot as plt

In [2]: plt.plot([1,2,3],[4,5,6])
Out[2]: [<matplotlib.lines.Line2D at 0x30b2b10>]

In [3]: ax = plt.gca() # get axis handle

In [4]: line = ax.lines[0] # get the first line, there might be more

In [5]: line.get_xdata()
Out[5]: array([1, 2, 3])

In [6]: line.get_ydata()
Out[6]: array([4, 5, 6])

In [7]: line.get_xydata()
Out[7]: 
array([[ 1.,  4.],
       [ 2.,  5.],
       [ 3.,  6.]])

I found these by digging around in the axis object. I could only find some minimal information about these functions, apperently you can give them a boolean flag to get either original or processed data, not sure what the means.

Edit: Joe Kington showed a slightly neater way to do this:

In [1]: import matplotlib.pyplot as plt

In [2]: lines = plt.plot([1,2,3],[4,5,6],[7,8],[9,10])

In [3]: lines[0].get_data()
Out[3]: (array([1, 2, 3]), array([4, 5, 6]))

In [4]: lines[1].get_data()
Out[4]: (array([7, 8]), array([ 9, 10]))