为什么这个情节的底部有额外的空间?

时间:2014-05-05 17:25:49

标签: python numpy graph matplotlib bar-chart

我刚刚使用matplotlib创建了一个水平堆积条形图,我无法弄清楚为什么x轴和第一个条之间有额外的空间(下面的代码和图片)。有什么建议或问题吗?谢谢!

代码:

fig = figure(facecolor="white")
ax1 = fig.add_subplot(111, axisbg="white")
heights = .43
data = np.array([source['loan1'],source['loan2'],source['loan3']])
dat2 = np.array(source2)
ind=np.arange(N)
left = np.vstack((np.zeros((data.shape[1],), dtype=data.dtype), np.cumsum(data, axis=0) [:-1]))
colors = ( '#27A545', '#7D3CBD', '#C72121')

for dat, col, lefts, pname2 in zip(data, colors, left, pname):
    ax1.barh(ind+(heights/2), dat, color=col, left=lefts, height = heights, align='center', alpha = .5)

p4 = ax1.barh(ind-(heights/2), dat2, height=heights, color = "#C6C6C6", align='center', alpha = .7)

ax1.spines['right'].set_visible(False)
ax1.yaxis.set_ticks_position('left')
ax1.spines['top'].set_visible(False)
ax1.xaxis.set_ticks_position('bottom')
yticks([z for z in range(N)], namelist)

#mostly for the legend
params = {'legend.fontsize': 8}
rcParams.update(params)
box = ax1.get_position()
ax1.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])
l = ax1.legend(loc = 'upper center', bbox_to_anchor=(0.5,-0.05), fancybox=True, shadow = True, ncol = 4)

show()

enter image description here

1 个答案:

答案 0 :(得分:2)

这是因为默认情况下matplotlib会尝试智能地选择绘图的最小和最大限制(即" round-ish"数字)。

这对某些情节很有意义,但对其他情节却没有。

要禁用它,只需执行ax.axis('tight')即可将数据限制捕捉到严格的数据范围。

如果你想要一点填充,尽管"紧"在轴限制上的边界,使用ax.margins

在您的情况下,您可能需要以下内容:

# 5% padding on the y-axis and none on the x-axis
ax.margins(0, 0.05)

# Snap to data limits (with padding specified above)
ax.axis('tight')

另外,如果要手动设置范围,可以执行

ax.axis([xmin, xmax, ymin, ymax])` 

或使用set_xlimset_ylim,甚至

ax.set(xlim=[xmin, xmax], ylim=[ymin, ymax], title='blah', xlabel='etc')
相关问题