简体   繁体   中英

Python save matplotlib figure with exact pixel size

I want to save an matplotlib figure with an exact size in pixels. In the code below, this exact size is 500x500 pixels. Whilst the saved image is 500x500 pixels it includes padding around my shape and plot area. I want the circle to be tight to the borders. Instead there is white space around my circle. Is it possible to save the plotting area only? Please note that while the code below is reproducible, my_dpi is dependant upon your monitor DPI. 220 is my display's DPI.

import matplotlib.pyplot as plt
import matplotlib.image as mpimage
import numpy as np

H       = 500
W       = 500
radius  = H/2
my_dpi  = 220


a = np.deg2rad(0)
b = np.deg2rad(360);

t = np.linspace(a,b,100)
x = radius*np.cos(t)
y = radius*np.sin(t)
x = np.append(x,[0,x[0]])
y = np.append(y,[0,y[0]])

myFig   = plt.figure()
DPI     = my_dpi #myFig.get_dpi()
myFig.set_size_inches(float(H)/float(DPI),float(W)/float(DPI))

plt.fill(y,x,color='none',facecolor='red')
plt.axis((-W/2,W/2,-H/2,H/2))
plt.axis('off')
#plt.show()
plt.savefig('my_fig.png',dpi=DPI)

print 'Figure Size: ', myFig.get_size_inches()

Im = mpimage.imread('my_fig.png')
print 'Im Size: ', Im.shape

You can use subplots_adjust to set the padding around your plot.

myFig.subplots_adjust(bottom=0.,left=0.,right=1.,top=1.)

在此输入图像描述

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