带有注释的Matplotlib与保存的图形截断

use*_*012 22 python matplotlib

我正在使用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)
Run Code Online (Sandbox Code Playgroud)

ODi*_*lva 43

bbox_inches参数保存数字

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