The Python Oracle

How to remove axis, legends, and white padding

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC P Beethoven - Piano Sonata No 2 in A

--

Chapters
00:00 Question
00:45 Accepted answer (Score 612)
01:42 Answer 2 (Score 183)
02:14 Answer 3 (Score 84)
02:49 Answer 4 (Score 45)
03:14 Thank you

--

Full question
https://stackoverflow.com/questions/9295...

Accepted answer links:
[axis('off')]: https://matplotlib.org/stable/api/_as_ge...

Answer 2 links:
[matehat, here]: https://stackoverflow.com/q/8218887/1905...

Answer 4 links:
[imsave]: https://matplotlib.org/devdocs/api/_as_g...
[image]: https://i.stack.imgur.com/NQv8Z.png

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #matplotlib

#avk47



ACCEPTED ANSWER

Score 646


The axis('off') method resolves one of the problems more succinctly than separately changing each axis and border. 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.

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

from numpy import random
import matplotlib.pyplot as plt

data = 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




ANSWER 2

Score 199


I learned this trick from matehat, here:

import matplotlib.pyplot as plt
import numpy as np

def 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




ANSWER 3

Score 91


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




ANSWER 4

Score 50


No one mentioned imsave yet, which makes this a one-liner:

import matplotlib.pyplot as plt
import numpy as np

data = np.arange(10000).reshape((100, 100))
plt.imsave("/tmp/foo.png", data, format="png", cmap="hot")

It directly stores the image as it is, i.e. does not add any axes or border/padding.

enter image description here