gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:14 28 4
gpt4 key购买 nike

我是 matplotlib 的新手,一瘸一拐地学习。尽管如此,我还没有找到这个问题的明显答案。

我有一个散点图,我想按组着色,它看起来像 plotting via a loopway to roll .

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

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')

取消注释 plt.show() 会得到我想要的结果:

good plot

找了一圈,好像plt.savefig()是保存文件的方法;如果我重新注释掉 plt.show() 并改为运行 plt.savefig(),我会得到一张空白的白色图片。 This question ,表明这是通过在 savefig() 之前调用 show() 引起的,但我已将其完全注释掉。 Another question有评论建议我可以直接保存 ax 对象,但这切断了我的图例:

chopped legend

同样的问题有一个替代方案,它使用 fig.savefig() 代替。我得到了同样的切碎图例。

this question这似乎是相关的,但我没有直接绘制 DataFrame 所以我不确定如何应用答案(其中 dtfpd.DataFrame 他们在密谋):

plot = dtf.plot()
fig = plot.get_figure()
fig.savefig("output.png")

感谢您的任何建议。


编辑: 测试下面的建议以尝试 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')

最佳答案

删除行 plt.figure(figsize=(12, 9)) 它将按预期工作。 IE。在 show 之前调用 savefig

问题是正在保存的图形是由 plt.figure() 创建的,而所有数据都绘制到 ax 之前创建的(并以不同的图形显示,这不是被保存的图形)。

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

plt.savefig('test.png', bbox_inches="tight")

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

fig.savefig('test.png', bbox_inches="tight")

要更深入地了解如何将图例移出情节,请参阅 this answer .

关于python - 将 matplotlib 子图图形保存到图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47956746/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com