Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib get clean plot (remove all decorations)

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?

like image 335
theta Avatar asked Jul 07 '26 17:07

theta


1 Answers

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):

enter image description here

tight.png (521x414):

enter image description here

like image 143
unutbu Avatar answered Jul 09 '26 06:07

unutbu