【问题标题】:matplotlib savefig image size with bbox_inches='tight'matplotlib savefig 图像大小与 bbox_inches='tight'
【发布时间】:2012-10-12 15:46:34
【问题描述】:

我必须制作一个矢量图,我只想看到没有轴、标题等的向量,所以我尝试这样做:

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 x 1600 的图像,但我还是得到了一个 775 x 1280 的图像。如何使其达到所需的尺寸? 谢谢。

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

【问题讨论】:

  • 使用 MPL,您必须保持两个 DPI 值。您在创建figure 对象时指定的对象是用于在屏幕上交互式显示图形。调用savefig 时指定的另一个DPI 值适用于保存的文件(以任何格式)。这就是@unutbu 发布的解决方案有效的原因。

标签: python matplotlib


【解决方案1】:
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)

产量

您可以通过将图形设置为 5x8 英寸来使结果图像为 1000x1600 像素

fig.set_size_inches(5, 8)

并使用DPI=200保存:

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

移除边框的代码取自here

(上面贴的图片没有按比例缩放,因为 1000x1600 相当大)。

【讨论】:

    猜你喜欢
    • 2014-10-30
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 2012-10-15
    • 2011-03-08
    • 2018-01-04
    相关资源
    最近更新 更多