在 matplotlib 中使用 bbox_inches='tight' 时,如何获得以像素为单位的精确大小的图像? [英] How do I get an image w/ the exact size in pixels, when using bbox_inches='tight' in matplotlib?

查看:93
本文介绍了在 matplotlib 中使用 bbox_inches='tight' 时,如何获得以像素为单位的精确大小的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将图形绘制为精确的分辨率(例如800x600),但是当使用 bbox_inches ='tight '时,这些图并不是全分辨率的,而是较小的.我可以将以英寸为单位的图像大小手动设置为大约(9.2,6.5),这将导致799 x 601,但我希望有更好的解决方案.可以在调整大小之前设置 bbox_inches ='tight'吗?

I want to plot graphs to an exact resolution (e.g. 800x600), but when using bbox_inches='tight' the plots are not at full resolution, they are smaller. I can manually set the image size in inches to about (9.2, 6.5), which results in 799 x 601, but I hope there is a better solution. Can you set bbox_inches='tight' before adjusting the size?

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)

https://img707.imageshack.us/img707/2192/exactsizetest.png

推荐答案

您想使用 tight_layout

You want to use tight_layout(doc) before calling savefig

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)

这篇关于在 matplotlib 中使用 bbox_inches='tight' 时,如何获得以像素为单位的精确大小的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆