As a reference, same question but for imshow(): Matplotlib plots: removing axis, legends and white spaces
It is not obvious in embedded image on selected answer that there are fat white margins around the plot, as stackoverflow page background is white.
The following answer by @unutbu works for imshow() but not for general plot(). Also aspect='normal is deprecated since version 1.2.
So how to save plot() as image, without any decorations?
ax.set_axis_off(), or equivalently, ax.axis('off') toggles the axis lines and labels off. To remove more whitespace, you could use
fig.savefig('/tmp/tight.png', bbox_inches='tight', pad_inches=0.0)
Or to remove all whitespace up to the axis' boundaries, use
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('/tmp/extent.png', bbox_inches=extent)
These commands will work equally well with either ax.imshow(data) or ax.plot(data).
For example,
import numpy as np
import matplotlib.pyplot as plt
data = np.arange(1,10).reshape((3, 3))
fig, ax = plt.subplots()
ax.plot(data)
ax.axis('off')
# https://stackoverflow.com/a/4328608/190597 (Joe Kington)
# Save just the portion _inside_ the axis's boundaries
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('/tmp/extent.png', bbox_inches=extent)
fig.savefig('/tmp/tight.png', bbox_inches='tight', pad_inches=0.0)
extent.png (504x392):

tight.png (521x414):

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With