manipulating top and bottom margins in pyplot horizontal stacked bar chart (barh)

2k views Asked by At

I'm trying to plot a horizontal stacked bar chart but get annoyingly big margins on top and bottom. I would like to get rid of that or control the size.

Here is an example code and fig:

from random import random
Y = ['A', 'B', 'C', 'D', 'E','F','G','H','I','J', 'K']
y_pos = np.arange(len(Y))
data = [(r, 1-r) for r in [random() for i in range(len(Y))]]
print data
a,b = zip(*data)

fig = plt.figure(figsize=(8,16))
ax = fig.add_subplot(111)
ax.barh(y_pos, a,color='b',align='center')
ax.barh(y_pos, b,left=a,color='r',align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(Y, size=16)
ax.set_xlabel('X label', size=20)

plt.xlim(0,1) #removing the extra x on the right side

If you want to recreate the exact figure, the sequence sampled creating the attached figure ('data'):

[(0.2180251581652276, 0.7819748418347724), (0.20639063565084814, 0.7936093643491519), (0.5402540115461549, 0.45974598845384507), (0.39283183355790896, 0.607168166442091), (0.5082547993681953, 0.4917452006318047), (0.02489004061858613, 0.9751099593814139), (0.25902114354397665, 0.7409788564560233), (0.12032683729286475, 0.8796731627071352), (0.41578415717252204, 0.584215842827478), (0.5860546624151288, 0.4139453375848712), (0.20982523758445237, 0.7901747624155476)]

enter image description here

I'd like to have a much smaller gap on top of 'K' and between the x axis and 'A'. If I change the 16 in:

fig = plt.figure(figsize=(8,16))

to 10 the everything shrinks but the margins are still relatively large.

Any ideas? Thanks!

1

There are 1 answers

1
Primer On BEST ANSWER

You might want to add this line to the end of your script:

plt.ylim(min(y_pos)-1, max(y_pos)+1)

This will reduce the margins to a half-a-bar width.