Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 559
keyserSoze Avatar asked Feb 13 '15 01:02

keyserSoze


1 Answers

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

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

enter image description here

like image 159
tmdavison Avatar answered Nov 08 '22 09:11

tmdavison