2010-06-28 244 views
25

下面的示例代码将产生无轴的基本线图,并将其保存为一个SVG文件:Matplotlib savefig图像裁剪

import matplotlib.pyplot as plt 
plt.axis('off') 
plt.plot([1,3,1,2,3]) 
plt.plot([3,1,1,2,1]) 
plt.savefig("out.svg", transparent = True) 

如何设置分辨率的图像/尺寸是多少?在线图之外的图像的所有边上都有填充。如何删除填充以便线条出现在图像的边缘?

回答

45

我总是惊讶于在matplotlib中有多少种方法可以做同样的事情。因此,我确信有人可以使这个代码更加简洁。
无论如何,这应该清楚地表明如何去解决你的问题。

>>> import pylab 
>>> fig = pylab.figure() 

>>> pylab.axis('off') 
(0.0, 1.0, 0.0, 1.0) 
>>> pylab.plot([1,3,1,2,3]) 
[<matplotlib.lines.Line2D object at 0x37d8cd0>] 
>>> pylab.plot([3,1,1,2,1]) 
[<matplotlib.lines.Line2D object at 0x37d8d10>] 

>>> fig.get_size_inches() # check default size (width, height) 
array([ 8., 6.]) 
>>> fig.set_size_inches(4,3) 
>>> fig.get_dpi()   # check default dpi (in inches) 
80 
>>> fig.set_dpi(40) 

# using bbox_inches='tight' and pad_inches=0 
# I managed to remove most of the padding; 
# but a small amount still persists 
>>> fig.savefig('out.svg', transparent=True, bbox_inches='tight', pad_inches=0) 

Documentation对于savefig()

+4

有没有办法把这些放在matplotlibrc中? '坏钥匙'savefig.bbox_inches“' – endolith 2012-07-08 00:59:08

+0

非常欢迎您。我不知道是否可以使用matplotlibrc文件来提供这样的配置规范。 – bernie 2013-01-25 16:49:40

+0

pyplot中另一个我喜欢使用的命令(与上面列出的命令一起使用)是plt.tight_layout(),它可以消除图形周围的多余空白。 – Blink 2014-03-04 16:23:03

2

默认的轴对象为标题,刻度标签等留下了一些空间。使填充整个区域自己的轴对象:

fig=figure() 
ax=fig.add_axes((0,0,1,1)) 
ax.set_axis_off() 
ax.plot([3,1,1,2,1]) 
ax.plot([1,3,1,2,3]) 
fig.savefig('out.svg') 

SVG格式,我不能看到这是正确的底部线,但PNG格式,我可以,所以它可能是SVG渲染器的功能。您可能只需添加一点填充以保持一切可见。

+0

正确。您可以通过手动调整轴来调整图中轴的位置。用于制作坐标轴的pyplot(或pylab)命令在其文档字符串中包括: 坐标轴(rect,axisbg ='w'),其中rect = [left,bottom,width,height]为标准化的(0,1)单位。 axisbg是轴的背景颜色,默认为白色 – timbo 2011-01-16 03:55:45