从 savefig() 上的 matplotlib 图形中剪切的文本或图例 [英] Text or legend cut from matplotlib figure on savefig()

查看:29
本文介绍了从 savefig() 上的 matplotlib 图形中剪切的文本或图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我想绘制一个非常简单的图形,其中2子图水平放置,我想在第二个子图的右边添加一些文本.我在 Jupyter Notebook 工作,但这不会改变任何事情:

 将matplotlib.pyplot导入为plt%matplotlib 内联plt.figure(figsize =(8,3))ax1 = plt.subplot(121)ax1.plot(x,y1)ax2 = plt.subplot(122)ax2.plot(x,y2)ax2.text(1.05,0.7, '这里有一些文字', horizo​​ntalalignment='left', transform=ax2.transAxes)

显示的输出和我想要的一样:

但是,当我尝试导出图形时,右侧的文本被剪切:

plt.savefig(r'C:\mypy\test_graph.png', ext='png');

按照建议

Say I want to plot a very simple figure with 2-subplot laid out horizontally, and I want to add some text on the right of the second subplot. I am working in Jupyter Notebook, but this shouldn't change anything:

import matplotlib.pyplot as plt
%matplotlib inline

plt.figure(figsize=(8, 3))

ax1 = plt.subplot(121)
ax1.plot(x,y1)

ax2 = plt.subplot(122)
ax2.plot(x,y2)
ax2.text(1.05,0.7, 'Some text here', horizontalalignment='left', transform=ax2.transAxes)

The displayed output is just as I want it:

However, when I try to export the figure, the text to the right get cut:

plt.savefig(r'C:\mypy\test_graph.png', ext='png');

Using plt.tightlayout(), as suggested here makes the problem worse.

How can I best resolve this?

解决方案

Jupyter notebook is by default configured to use its "inline" backend (%matplotlib inline). It displays a saved png version of the figure. During this saving, the option bbox_inches="tight" is used.

In order to replicate the figure that you see in the jupyter output, you would need to use this option as well.

plt.savefig("output.png", bbox_inches="tight")

What this command does is to extend or shrink the area of the saved figure to include all the artists in it.

Alternatively, you can shrink the content of the figure, such that there is enough space for the text to fit into the original figure.

This can be done with e.g.

plt.subplots_adjust(right=0.7)

which would mean that the rightmost axes stops at 70% of the figure width.

这篇关于从 savefig() 上的 matplotlib 图形中剪切的文本或图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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