Say I create a simple scatter plot, and I set the figure up to be 8x6 inches and 100 dpi:
import matplotlib.pyplot as plt
data = ([1, 2, 3, 4], [1, 2, 3, 4])
plt.figure(figsize=(8, 6), dpi=100) # draw figure
plt.axis([1, 4, 1, 4]) # set axis limits
plt.scatter(*data) # plot data
plt.savefig('plot_full.png') # save image
plt.show()
plt.close()
As expected, the output image has dimensions of 800x600 pixels. No problem here.
Now say I create the same scatter plot, but I want the output image to be only the actual plot area. That is, no title or axis labels, no tick marks, and no border or padding of any sort. I can achieve this using plt.axis(False)
and including bbox_inches='tight', pad_inches=0
as arguments in plt.savefig()
:
import matplotlib.pyplot as plt
data = ([1, 2, 3, 4], [1, 2, 3, 4])
plt.figure(figsize=(8, 6), dpi=100) # draw figure
plt.axis([1, 4, 1, 4]) # set axis limits
plt.axis(False) # remove x and y axes from figure
plt.scatter(*data) # plot data
plt.savefig('plot_crop.png', bbox_inches='tight', pad_inches=0) # save image
plt.show()
plt.close()
This time, the output image has dimensions of 620x453 pixels. Opening both images in an editor, it is clear that this is simply the same as plotfull.png, but cropped down to the actual plot area.
How can I change this to output an image like plotcrop.png, but at the original resolution of 800x600 pixels?
Edit: Solution
This code will generate the correct image:
import matplotlib.pyplot as plt
data = ([1, 2, 3, 4], [1, 2, 3, 4])
fig = plt.figure(figsize=(8, 6), dpi=100) # draw figure
plt.axis([1, 4, 1, 4]) # set axis limits
plt.axis(False) # remove x and y axes from figure
plt.scatter(*data) # plot data
fig.tight_layout(pad=0) # tight layout
plt.savefig('plot_crop.png') # save image
plt.show()
plt.close()
Notice that here, the plot.figure()
object is assigned to a variable fig
, with which tight_layout
is called. Obviously, make sure to call fig.tight_layout(pad=0)
after removing the axes with plt.axis(False)
.