python - 如何知道用 pandas 用 python 完成的图表的图形引用?

标签 python pandas matplotlib

我需要迭代用 matplotlib 完成的几个图形。 只有其中一张图是通过 Pandas 可视化“直接”完成的。 下面的代码将展示一个只有 2 个图的示例,一个是使用 matplotlib API 完成的,另一个是直接使用 Pandas 完成的。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

dates   = pd.date_range('20000101', periods=10)
df      = pd.DataFrame(index=dates)
df['A'] = np.cumsum(np.random.randn(10))  
df['B'] = np.random.randint(-1,2,size=10)
df['i'] = range(1,11)

# first figure done with matplotlib API
fig1    = plt.figure()
ax1     = plt.subplot2grid((5,1),(0,0), rowspan=5, colspan=1)
ax1     = ax1.plot(df.A)


# second figure done with pandas
fig2    = plt.figure()
ax_bar  = df[df.columns].tail(1).plot(kind='bar',legend=True)
ax_bar.xaxis.set_visible(False)

如果你运行这段代码,你实际上会得到 3 个数字。

第一个图是正确的Fig1,第二个图是空白的Fig2,第三个图是ax_bar图表。

type(ax_bar) 为您提供 matplotlib.axes._subplots.AxesSubplot

所以我的问题是,我如何知道或定义与 ax_bar 图关联的图形的名称?

因为目标是最终可以迭代所有数字,所以例如:

figures = [fig1,fig2],因此 figures 是一个列表,可以迭代它(以便能够完成另一个需要完成的过程) ,但这目前无法完成,因为Fig2是空白的,我不知道如何调用用pandas完成的图。

最佳答案

您可以使用plt.gcf()使用 Pandas 绘图后获取当前图形:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

dates   = pd.date_range('20000101', periods=10)
df      = pd.DataFrame(index=dates)
df['A'] = np.cumsum(np.random.randn(10))  
df['B'] = np.random.randint(-1,2,size=10)
df['i'] = range(1,11)

# first figure done with matplotlib API
fig1    = plt.figure()
ax1     = plt.subplot2grid((5,1),(0,0), rowspan=5, colspan=1)
ax1     = ax1.plot(df.A)

# second figure done with pandas
ax_bar  = df[df.columns].tail(1).plot(kind='bar',legend=True)
ax_bar.xaxis.set_visible(False)
fig2 = plt.gcf() # <- use this

figures = [fig1,fig2]
for fig in figures:
    print(fig)

结果:

>>> for fig in figures:
...     print(fig)
...
Figure(640x440)
Figure(640x440)

关于python - 如何知道用 pandas 用 python 完成的图表的图形引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42867239/

相关文章:

使用 pm2 时 python 模块导入失败

python - Pandas 仅对某些列求和和计数

python - pandas 多个图不能作为主机工作

python - Seaborn 直方图 bin 宽度未扩展到 bin 标签

python - 将 'unorthodox' 轴标签添加到 pyplot

python - 列表中的两个不同的 random.choices (python)

python - 当鼠标悬停在窗口上时在 Tkinter 中显示按钮

python - 从具有列索引的元组列表创建一个稀疏矩阵,其中 1

pandas - 如何使用 pandas 数据框计算列的平均脉冲计数?

python - 如何通过 Pandas 中不同的列值重组每日时间序列?