Matplotlib:从 iPython 笔记本中将图形另存为文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19271309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:18:34  来源:igfitidea点击:

Matplotlib: Save figure as file from iPython notebook

pythonmatplotlibipython-notebook

提问by Martin Preusse

I am trying to save a Matplotlib figure as a file from an iPython notebook.

我正在尝试将 Matplotlib 图保存为 iPython 笔记本中的文件。

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_axes([1,1,1,1])
ax.plot([1,2])

fig.savefig('test.png')


The inline view in the iPython notebook looks good:

iPython 笔记本中的内联视图看起来不错:

Inline view of figure in iPython notebook

iPython 笔记本中图形的内联视图



The file 'test.png' is almost empty though. It looks like the plot is shifted to the top right, you can see the tick labels '1.0' and '0.0' in the corner.

'test.png' 文件几乎是空的。看起来图移到了右上角,您可以在角落看到刻度标签“1.0”和“0.0”。

test.png

测试.png

How can I produce a file from the iPython notebook that looks like the inline view?

如何从 iPython 笔记本中生成一个看起来像内联视图的文件?

采纳答案by Martin Preusse

Problem solved: add 'bbox_inches='tight'argument to savefig.

问题已解决:'bbox_inches='tight'向 savefig添加参数。

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_axes([1,1,1,1])
plt.plot([1,2])

savefig('test.png', bbox_inches='tight')

I don't understand what's happening here, but the file looks like the iPython notebook inline file now. Yay.

我不明白这里发生了什么,但该文件现在看起来像 iPython 笔记本内联文件。好极了。

回答by tbekolay

Actually, the savefigis working properly. When you call add_axes, your list specifies a rectangle: [left, bottom, width, height]. Since the figure goes from 0 to 1 on both axes with the origin at the bottom left, you're making a rectangle of width and height 1 starting from the very top-right of the figure. You likely want to be doing ax = fig.add_axes([0,0,1,1]).

实际上,savefig它运行正常。当您调用 时add_axes,您的列表会指定一个矩形:[left, bottom, width, height]。由于图形在两个轴上从 0 到 1 且原点位于左下角,因此您将从图形的最右上角开始制作一个宽度和高度为 1 的矩形。你可能想要做的ax = fig.add_axes([0,0,1,1])

I'm not sure why the inline plot doesn't respect where you've placed the axes. If I had to guess, I would say that the inline backend automatically figures out the bounding box and places the inline figure according to that.

我不确定为什么内联图不尊重您放置轴的位置。如果我不得不猜测,我会说内联后端会自动计算出边界框并根据它放置内联图。