Python 从 matplotlib 图检索 XY 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20130768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve XY data from matplotlib figure
提问by brettb
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.
我正在用 wxPython 编写一个小应用程序,它有一个 matplotlib 图(使用 wxagg 后端)面板。我想为用户添加将图形中当前绘制的 X、Y 数据导出到文本文件的功能。有没有一种非侵入性的方法来做到这一点?我已经搜索了很多,似乎找不到任何东西,尽管我觉得它非常简单并且就在我面前。
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 ;)
编辑:澄清一下,我想知道如何做的是获取 X、Y 数据。之后写入文本文件很简单;)
采纳答案by Bas Swinckels
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 informationabout 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:
编辑:Joe Kington 展示了一种更简洁的方法来做到这一点:
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]))

