matplotlib使用bbox_inches ='tight'保存图像大小

时间:2012-10-22 19:11:21

标签: python matplotlib

我必须制作一个矢量图,我想只看到没有轴,标题等的矢量,所以这就是我尝试的方法:

pyplot.figure(None, figsize=(10, 16), dpi=100)
pyplot.quiver(data['x'], data['y'], data['u'], data['v'], 
              pivot='tail', 
              units='dots', 
              scale=0.2,
              color='black')

pyplot.autoscale(tight=True)
pyplot.axis('off')
ax = pyplot.gca()
ax.xaxis.set_major_locator(pylab.NullLocator())
ax.yaxis.set_major_locator(pylab.NullLocator())
pyplot.savefig("test.png", 
               bbox_inches='tight', 
               transparent=True,
               pad_inches=0)

尽管我努力使图像1000乘1600,但我得到一个775乘1280.我如何使它达到所需的尺寸? 谢谢。

更新提供的解决方案有效,除了在我的情况下我还必须手动设置轴限制。否则,matplotlib无法找出“紧”的边界框。

1 个答案:

答案 0 :(得分:16)

import matplotlib.pyplot as plt
import numpy as np
sin, cos = np.sin, np.cos

fig = plt.figure(frameon = False)
fig.set_size_inches(5, 8)
ax = plt.Axes(fig, [0., 0., 1., 1.], )
ax.set_axis_off()
fig.add_axes(ax)

x = np.linspace(-4, 4, 20)
y = np.linspace(-4, 4, 20)
X, Y = np.meshgrid(x, y)
deg = np.arctan(Y**3-3*Y-X)
plt.quiver(X, Y, cos(deg), sin(deg), pivot = 'tail', units = 'dots', color = 'red', )
plt.savefig('/tmp/test.png', dpi = 200)

产量

enter image description here

通过将图形设置为5x8英寸

,可以将结果图像设置为1000x1600像素
fig.set_size_inches(5, 8)

并使用DPI = 200保存:

plt.savefig('/tmp/test.png', dpi = 200)

删除边框的代码取自here

(上面张贴的图片不按比例,因为1000x1600相当大。)

相关问题