[英]How to extract x,y data from kdensity plot from matplotlib for python
[英]How to extract data from matplotlib plot
我有一個wxPython
程序,它從不同的數據集讀取數據,對數據執行各種類型的簡單即時分析,並將數據集的各種組合繪制到matplotlib
畫布上。 我希望有機會將當前繪制的數據轉儲到文件中,以便稍后進行更復雜的分析。
問題是: matplotlib
中是否有任何方法允許訪問當前在matplotlib.Figure
繪制的數據?
Jakub 修改 Python 腳本以直接從數據發送到繪圖的源中寫出數據是正確的; 這就是我更喜歡這樣做的方式。 但是作為參考,如果您確實需要從繪圖中獲取數據,我認為應該這樣做
gca().get_lines()[n].get_xydata()
或者,您可以分別獲取 x 和 y 數據集:
line = gca().get_lines()[n]
xd = line.get_xdata()
yd = line.get_ydata()
matplotlib.pyplot.gca
可用於從 matplotlib 圖中提取數據。 這是一個簡單的例子:
import matplotlib.pyplot as plt
plt.plot([1,2,3],[4,5,6])
ax = plt.gca()
line = ax.lines[0]
line.get_xydata()
運行此程序時,您將看到 2 個輸出 - 繪圖和數據:
array([[1., 4.],
[2., 5.],
[3., 6.]])
您還可以分別獲取 x 數據和 y 數據。 在運行line.get_xdata()
,您將獲得:
array([1, 2, 3])
在運行line.get_ydata()
,您將獲得:
array([4, 5, 6])
注意: gca
代表獲取當前軸
它是 Python,因此您可以直接修改源腳本,以便在繪制數據之前轉儲數據
我知道這是一個老問題,但我覺得有一個比這里提供的解決方案更好的解決方案,所以我決定寫下這個答案。
您可以使用unittest.mock.patch
臨時替換matplotlib.axes.Axes.plot
函數:
from unittest.mock import patch
def save_data(self, *args, **kwargs):
# save the data that was passed into the plot function
print(args)
with patch('matplotlib.axes.Axes.plot', new=save_data):
# some code that will eventually plot data
a_function_that_plots()
一旦退出with
塊, Axes.plot
將恢復正常行為。
總結一下,供以后參考:
如果使用plt.plot()
或plt.stem()
或plt.step()
繪圖,您可以獲得 Line2D 對象的列表:
ax = plt.gca() # to get the axis
ax.get_lines()
對於plt.pie()
、 plt.bar()
或plt.barh()
您可以獲得楔形或矩形對象的列表:
ax = plt.gca() # to get the axis
ax.patches()
然后,根據情況,您可以通過運行get_xdata()
、 get_ydata()
(請參閱Line2D )獲取數據以獲取更多信息。
或即get_height()
用於條形圖(請參閱Rectangle )了解更多信息。
一般來說,對於所有基本繪圖功能,您可以通過運行ax.get_children()找到您要查找的內容
返回子Artists
的列表(基類包括圖形的所有元素)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.