从保存的figu中切断注释的Matplotlib

2024-04-28 21:47:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用matplotlib在使用注释时绘制一些图形。我遇到的问题是,注释(位于绘图区域之外)与保存的图片断开,如下图所示。

figure with annotations cut off

下图是我想要的:

The desired picture

有人知道怎么解决这个问题吗?我注意到有人建议在rcParams中使用plt.tight_plot()或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)

Tags: 图形dataplotfigpltaxdictxy