在pyplot水平堆积条形图(barh)中操纵顶部和底部边距

时间:2015-06-16 03:09:00

标签: python matplotlib margins

我正在尝试绘制一个水平堆积的条形图,但在顶部和底部获得了令人烦恼的大边距。我想摆脱它或控制大小。

这是一个示例代码和图:

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

如果要重新创建确切的数字,则采样的序列创建附图('数据'):

[(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

我希望在'K'之上以及x轴和'A'之间有一个小得多的间隙。 如果我改变16 in:

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

到10,一切都在缩小,但利润仍然相对较大。

有什么想法吗? 谢谢!

1 个答案:

答案 0 :(得分:3)

您可能希望将此行添加到脚本的末尾:

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

这会将边距减少到半个条宽。