如何在matplotlib中使用bbox_inches='tight'时获取精确像素大小的图像?
我想要绘制精确分辨率的图表,比如800x600的大小。但是当我使用 bbox_inches='tight'
时,图表的大小并没有达到全分辨率,而是变得更小了。
我可以手动设置图像的尺寸为大约(9.2, 6.5)英寸,这样得到的结果是799 x 601,但我希望能有更好的解决办法。有没有办法在调整大小之前就设置 bbox_inches='tight'
?
import matplotlib as mlp
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
x = y = np.arange(0, 1, 0.1)
plt.plot(x, y, label='my function')
plt.title('title')
ax.set_xlabel('xAxis')
ax.set_ylabel('yAxis')
#print fig.get_size_inches()
#fig.set_size_inches(9.2, 6.5)
plt.savefig('exact_size_test.png', bbox_inches='tight', dpi=100)
1 个回答
2
你想在调用 savefig
之前使用 tight_layout
,这样可以让图形的布局更加紧凑和美观。你可以查看这个 文档 来了解更多信息。
import matplotlib as mlp
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
x = y = np.arange(0, 1, 0.1)
plt.plot(x, y, label='my function')
plt.title('title')
ax.set_xlabel('xAxis')
ax.set_ylabel('yAxis')
#print fig.get_size_inches()
fig.set_size_inches(8, 6, forward=True)
fig.tight_layout()
plt.savefig('exact_size_test.png', dpi=100)