3

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?

Community
  • 1
  • 1
theta
  • 24,593
  • 37
  • 119
  • 159

2 Answers2

3

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

Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

I just learned that @unutbu's answer does work with plot() too, if we remove aspect='normal' from plot() directive:

data = np.arange(1,10).reshape((3, 3))
fig = plt.figure()
fig.set_size_inches(1, 1)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
ax.plot(data)
plt.savefig('test.png')

But, I still wonder if all this is really necessary to get clean plot?
Shouldn't be there obvious argument to savefig() that can handle this?

theta
  • 24,593
  • 37
  • 119
  • 159