Skip to main content
 首页 » 编程设计

python之如何从 Pandas 图中提取数据

2024年10月01日7zfyouxi

我有一个数据框,我正在用 ipython 中的 pandas 绘制它。我正在导入通常的东西,然后绘制数据框

import pandas as pd 
import matplotlib.pyplot as plt 
%matplotlib inline   
 
traydata_A[('x_TmId', 'Trays')].plot() 
plt.xlabel('Hour of the day') 
plt.ylabel('Number of picked/despatched trays') 

并希望通过使用(例如 this question )获取绘制的实际数据

ax = plt.gca()  
line = ax.lines[0] 

最终结果是

  IndexError                                Traceback (most recent call last) 
<ipython-input-220-d211b85302a5> in <module>() 
      1 ax = plt.gca() 
----> 2 line = ax.lines[0] 
 
IndexError: list index out of range 

我做错了什么?我确定我对pandas如何连接matplotlib有很深的误解!

请您参考如下方法:

您必须确保使用 pandas 图返回的坐标轴 function .在您的代码中,ax = plt.gca() 返回一个与 pandas 使用的轴不同的轴。要么确保在同一上下文中执行代码,要么将 pandas 轴保存到中间变量中。完整示例:

s = pd.Series(data=[5850000, 6000000, 5700000, 13100000, 16331452], name='data') 
ax = s.plot() 
print(ax.get_lines()[0].get_xydata()) 
[[  0.00000000e+00   5.85000000e+06] 
 [  1.00000000e+00   6.00000000e+06] 
 [  2.00000000e+00   5.70000000e+06] 
 [  3.00000000e+00   1.31000000e+07] 
 [  4.00000000e+00   1.63314520e+07]] 

来自 matplotlib.pyplot.gca 的文档:

Get the current Axes instance on the current figure matching the given keyword args, or create one.

[...]

If the current axes doesn’t exist [..] the appropriate axes will be created and then returned.