【问题标题】:savefig returns a blank imagesavefig 返回一个空白图像
【发布时间】:2020-05-27 01:09:46
【问题描述】:

我正在尝试使用 pandas 绘图功能绘制一个 pandas 数据框 (result_m),但是当我尝试使用 savefig 保存图形时,它返回一个空白 pdf。它在笔记本窗口中绘制得很好。不知道我做错了什么

fig = plt.figure()

ax = result_m.plot( kind='line',  figsize=(20, 10),fontsize=15)
ax.set_title('Harkins Slough Diversions',fontsize= 20) 
ax.set_xlabel( "Date",fontsize=18)
ax.set_ylabel("cubic meters",fontsize=18)
plt.legend(fontsize=15)

fig.savefig(os.path.join(outPath4,'plot_fig.pdf'))

【问题讨论】:

  • 这能回答你的问题吗? Matplotlib (pyplot) savefig outputs blank image
  • @AkibRhast 我认为这是一个稍微不同的问题,因为这涉及默认情况下不将熊猫图添加到 matplotlib 图中,而这些帖子大多直接处理 matplotlib,以及 plt.show 如何清除图。
  • 我明白了,我看到我谷歌 fig.savefig() 并且它带来了 matplotlib .. 所以我认为这就是他正在使用的东西? @MichaelDelgado 他的 savefig pandas 也是这样吗?
  • OP 正在使用 matplotlib.pyplot.Figure.savefig,这是一种 matplotlib 方法,但他们试图保存的绘图是使用 pandas.DataFrame.plot 生成的。

标签: python pandas matplotlib savefig


【解决方案1】:

问题是您创建的图不在您创建(并保存)的图形上。在第二行:

ax = result_m.plot( kind='line',  figsize=(20, 10),fontsize=15)

pandas 创建一个新图形,因为您没有提供轴 (ax) 参数。请参阅plotting to specific subplots 上的 pandas 文档。

您可以通过跳过图形创建步骤,然后从轴对象获取 pandas 创建的图形来解决此问题:

ax = result_m.plot( kind='line',  figsize=(20, 10),fontsize=15)
fig = ax.figure

或者通过将绘图添加到您创建的图形中,首先创建一个子图:

fig = plt.figure(size=(20, 10))
ax = fig.add_subplot(111)
ax = result_m.plot( kind='line',  fontsize=15, ax=ax)

请注意,在此选项中,请在创建图窗时定义图窗的size 属性,而不是将figsize 传递给DataFrame.plot

【讨论】:

    猜你喜欢
    • 2022-11-12
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 2014-03-27
    • 2012-06-03
    • 1970-01-01
    相关资源
    最近更新 更多