Matplotlib的注释已从保存的图形中删除 [英] Matplotlib with annotation cut off from the saved figure

查看:48
本文介绍了Matplotlib的注释已从保存的图形中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用matplotlib在使用注释时绘制一些图形.我遇到的问题是注释(在绘图区之外)从保存的图片中截断了,如下图所示.

I'm using matplotlib to draw something figure while using annotations. The problem I experienced is that the annotation (which is outside the plotting area) is cut off from the saved picture, as shown in the following figure.

下图是我想要的:

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

Anybody knows how to solve this problem? I noticed people suggest using plt.tight_plot() or fig.autolayout in rcParams, but that doesn't seem to work. Below is the code for producing the figure.

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

这篇关于Matplotlib的注释已从保存的图形中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆