简体   繁体   English

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

[英]Matplotlib: Save figure as file from iPython notebook

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 notebook 中的内联视图看起来不错:

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


The file 'test.png' is almost empty though.文件“test.png”几乎是空的。 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.看起来绘图移到了右上角,您可以在角落看到刻度标签“1.0”和“0.0”。

测试.png

How can I produce a file from the iPython notebook that looks like the inline view?如何从 iPython 笔记本中生成一个看起来像内联视图的文件?

Problem solved: add 'bbox_inches='tight' argument to savefig.问题已解决:在 savefig 中添加'bbox_inches='tight'参数。

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.我不明白这里发生了什么,但该文件现在看起来像 iPython 笔记本内联文件。 Yay.耶。

Actually, the savefig is working properly.实际上, savefig工作正常。 When you call add_axes , your list specifies a rectangle: [left, bottom, width, height] .当您调用add_axes时,您的列表指定一个矩形: [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.由于该图形在两个轴上从 0 变为 1,原点位于左下角,因此您从图形的右上角开始制作一个宽度和高度为 1 的矩形。 You likely want to be doing ax = fig.add_axes([0,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.如果我不得不猜测,我会说内联后端会自动计算出边界框并根据它放置内联图形。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM