将matplotlib子图图形保存到图像文件

Hen*_*ndy 4 python matplotlib figure

我是新来的matplotlib,正在lim步。就是说,我没有找到这个问题的明显答案。

我有一个散点图,希望按组进行着色,看起来像通过循环绘制滚动方式

这是我的可复制示例,基于上面的第一个链接:

import matplotlib.pyplot as plt
import pandas as pd
from pydataset import data

df = data('mtcars').iloc[0:10]
df['car'] = df.index

fig, ax = plt.subplots(1)
plt.figure(figsize=(12, 9))
for ind in df.index:
    ax.scatter(df.loc[ind, 'wt'], df.loc[ind, 'mpg'], label=ind)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2)
# plt.show()
# plt.savefig('file.png')
Run Code Online (Sandbox Code Playgroud)

取消注释会plt.show()产生我想要的东西:

好情节

到处搜索,看起来就像plt.savefig()是保存文件的方式。如果我重新注释掉plt.show()plt.savefig()改为运行,则会得到空白的白色图片。这个问题,暗示这是由于show()之前致电引起的savefig(),但我已将其完全注释掉了。另一个问题有一条评论,建议我可以ax直接保存该对象,但这切断了我的图例:

切碎的传说

相同的问题也有替代方法使用fig.savefig()。我得到同样的传说。

这个问题,这似乎有关,但我不密谋DataFrame直接,所以我不知道如何应用答案(这里dtfpd.DataFrame他们绘制):

plot = dtf.plot()
fig = plot.get_figure()
fig.savefig("output.png")
Run Code Online (Sandbox Code Playgroud)

感谢您的任何建议。


编辑:测试下面的建议尝试tight_layout(),我运行了这个,仍然得到一个空白的白色图像文件:

fig, ax = plt.subplots(1)
plt.figure(figsize=(12, 9))
for ind in df.index:
    ax.scatter(df.loc[ind, 'wt'], df.loc[ind, 'mpg'], label=ind)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2)
fig.tight_layout()
plt.savefig('test.png')
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 7

删除该行plt.figure(figsize=(12, 9)),它将按预期工作。即致电savefig之前show

问题在于,要保存的图形是由创建的图形plt.figure(),而绘制的所有数据都ax在此图形之前创建(在另一个图形中,不是保存的图形)。

要保存包括图例在内的图形,请使用bbox_inches="tight"选项

plt.savefig('test.png', bbox_inches="tight")
Run Code Online (Sandbox Code Playgroud)

当然也可以直接保存图形对象,

fig.savefig('test.png', bbox_inches="tight")
Run Code Online (Sandbox Code Playgroud)

要更深入地了解如何将图例移出情节,请参阅此答案