matplotlib savefig图像大小,带bbox_英寸class='tight'

2024-06-01 20:19:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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无法找到“紧密”边界框


Tags: 图像true标题data矢量axsetpyplot
1条回答
网友
1楼 · 发布于 2024-06-01 20:19:30
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相当大,上面发布的图像无法缩放)

相关问题 更多 >