Python matplotlib 不保存图表文件

Python matplotlib not saving charts files

我在数据库中有我持有的股票的历史数据。这里的对象是创建两个图表并将每个图表保存为 png 文件。我将数据库中的数据读入 pandas 数据框以构建图表。代码 运行s 很干净 - 没有错误。当我在 Spyder 中 运行 时,我看到了图表,但没有任何内容被保存。以下是我正在做的事情的简要总结:

fig1, ax1 = plt.subplots()
... some code
df['Price'].plot(ax=ax1, title=title1)
plt.savefig(figName1, bbox_inches='tight')
fig2, ax2 = plt.subplots()
... some code
df['% Price'].plot(ax=ax2, title=title2)
df['% S&P'].plot(ax=ax2)
plt.savefig(figName2, bbox_inches='tight')

这种方法有问题吗?谢谢

我认为问题在于,当您调用 DataFrame.plot() 时,它 returns 一个 matplotlib.axes.Axes 对象的 numpy 数组。尝试像这样使用 get_figure()

fig1 = df['Price'].plot(ax=ax1, title=title1).get_figure()
fig1.savefig(figName1, bbox_inches='tight')

或一行:

df['Price'].plot(ax=ax1, title=title1).get_figure().savefig(figName1, bbox_inches='tight')

已修复。显示的代码没有任何问题。问题出在 figName1 和 figName2 地址的格式上。尴尬。