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