6

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
1

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

This solved my problem of extra whitespace when hiding the axes on a plot with bbox_inches='tight'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.