简体   繁体   中英

How do I get an image w/ the exact size in pixels, when using bbox_inches='tight' in matplotlib?

I want to plot graphs to an exact resolution (eg 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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM