0

Using matplotlib.pyplot, I want to create a barplot, and save it to an image without axes, borders and additional whitespace around. The answers to Save spectrogram (only content, without axes or anything else) to a file using Matloptlib and all the linked questions and respective answers seem not to work for barplots.

So far I got:

import matplotlib.pyplot as plt

fig,ax = plt.subplots(1)
fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
fig.patch.set_facecolor('xkcd:mint green')
ax.set_facecolor('xkcd:salmon')
ax.axis('off')
ax.bar(1,1,1,-1,alpha=1, align='center', edgecolor='black')
ax.bar(2,1,1,-2,alpha=1, align='center', edgecolor='black')
ax.axis('off')
fig.savefig('test.png', dpi=300, frameon='false', pad_inches=0.0,bbox_inches='tight')

which has three issues:

  1. There is some remaining whitespace at the left,top and right.
  2. The figure seems to be cut at the bottom, as the bottom line of the lower bar is thinner than the others.
  3. The aspect ration should be 1:1 and seems to be off.

barplot output

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
Dschoni
  • 3,714
  • 6
  • 45
  • 80

1 Answers1

1
  1. The answer from the linked question does not use bbox_inches='tight'. This is contradictory to the wish to have no whitespace. In addition, there is of course also some margin inside the axes, because the bars of course do not sit directly at the axes borders. You may set ax.margins(0).
  2. A line extents to both directions of the coordinates, e.g. if you have a line of width 3 pixels at position 0, you'll get one pixel above 0, one pixel at 0 and one below 0. The one below 0 is cut if you restrict your image to start at position 0.
  3. There is no reason the aspect should be 1:1. But if you want it to be 1:1 you need to explicitely set it. ax.set_aspect(1). Of course this will only make sense if the figure is then also set to have equal width and height.

In total.

import matplotlib.pyplot as plt

fig,ax = plt.subplots(figsize=(5,5))
fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
fig.patch.set_facecolor('xkcd:mint green')
ax.set_facecolor('xkcd:salmon')
ax.axis('off')
ax.margins(0)
ax.set_aspect(1)
ax.bar(1,1,1,-1,alpha=1, align='center', edgecolor='black')
ax.bar(2,1,1,-2,alpha=1, align='center', edgecolor='black')

fig.savefig('test.png', dpi=300, frameon=False, pad_inches=0.0)

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712