Retrieve XY data from matplotlib figure [duplicate]

Solution 1:

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