带有注释的 Matplotlib 从保存的图形中删除

Matplotlib with annotation cut off from the saved figure

我正在使用 matplotlib 在使用注释的同时绘制图形。我遇到的问题是,标注(在绘图区外)被保存的图片截掉了,如下图。

下图就是我想要的:

有人知道怎么解决这个问题吗?我注意到人们建议在 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)

使用 bbox_inches 参数保存图形

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