Matplotlib plots: removing axis, legends and white spaces Matplotlib plots: removing axis, legends and white spaces python python

Matplotlib plots: removing axis, legends and white spaces


I think that the command axis('off') takes care of one of the problems more succinctly than changing each axis and the border separately. It still leaves the white space around the border however. Adding bbox_inches='tight' to the savefig command almost gets you there, you can see in the example below that the white space left is much smaller, but still present.

Note that newer versions of matplotlib may require bbox_inches=0 instead of the string 'tight' (via @episodeyang and @kadrach)

from numpy import randomimport matplotlib.pyplot as pltdata = random.random((5,5))img = plt.imshow(data, interpolation='nearest')img.set_cmap('hot')plt.axis('off')plt.savefig("test.png", bbox_inches='tight')

enter image description here


I learned this trick from matehat, here:

import matplotlib.pyplot as pltimport numpy as npdef make_image(data, outputname, size=(1, 1), dpi=80):    fig = plt.figure()    fig.set_size_inches(size)    ax = plt.Axes(fig, [0., 0., 1., 1.])    ax.set_axis_off()    fig.add_axes(ax)    plt.set_cmap('hot')    ax.imshow(data, aspect='equal')    plt.savefig(outputname, dpi=dpi)# data = mpimg.imread(inputname)[:,:,0]data = np.arange(1,10).reshape((3, 3))make_image(data, '/tmp/out.png')

yields

enter image description here


Possible simplest solution:

I simply combined the method described in the question and the method from the answer by Hooked.

fig = plt.imshow(my_data)plt.axis('off')fig.axes.get_xaxis().set_visible(False)fig.axes.get_yaxis().set_visible(False)plt.savefig('pict.png', bbox_inches='tight', pad_inches = 0)

After this code there is no whitespaces and no frame.

No whitespaces, axes or frame


matomo