保存的Matplotlib图中注释被截断

29

我在使用matplotlib绘制带注释的图形时遇到了问题。我发现注释(位于绘图区域之外)在保存的图片中被裁剪了,如下图所示:

figure with annotations cut off

我想得到以下所示的图像:

The desired picture

有人知道如何解决这个问题吗?我注意到有人建议使用plt.tight_plot()或在rcParams中使用fig.autolayout,但似乎都不起作用。下面是生成该图的代码:

fig, ax = plt.subplots()
ax.set_xlim([-0.02,1.1])
ax.set_ylim([-0.02,1.1])

ax.plot([0,0,0,0.5,0.5,0.5,1,1,1], [0,0.5,1,0,0.5,1,0,0.5,1], 'go')

ax.annotate("Digit 2",
            xy=(0.5, -0.1), xycoords='data',
            xytext=(0.5, -0.3), textcoords='data',
            arrowprops=dict(arrowstyle="->",
                            connectionstyle="arc3"),
             annotation_clip=False,
             fontsize = 12,
             ha='center',
            )

ax.annotate("Level 2",
            xy=(-0.1, 1), xycoords='data',
            xytext=(-0.35, 1), textcoords='data',
            arrowprops=dict(arrowstyle="->",
                            connectionstyle="arc3"),
                    annotation_clip=False,
                    fontsize = 12,
                    va='center',
            )

plt.savefig('sample.png', dpi = 300)
1个回答

57

使用bbox_inches参数保存图像

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

如果你的注释中有图片,这个方法不起作用。可以参考以下解决方案:https://stackoverflow.com/questions/56361175/why-is-picture-annotation-cropped-when-displaying-or-saving-figure/56370990#56370990 - flashliquid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接