【问题标题】:Why is there extra space at the bottom of this plot?为什么这个情节的底部有额外的空间?
【发布时间】:2014-06-22 02:10:14
【问题描述】:

我刚刚使用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()

【问题讨论】:

    标签: python numpy graph matplotlib bar-chart


    【解决方案1】:

    这是因为 matplotlib 默认尝试智能地选择绘图的最小和最大限制(即“圆形”数字)。

    这对某些情节很有意义,但对其他情节则不然。

    要禁用它,只需执行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')
    

    【讨论】:

    • 啊,如此简单的修复。我已经看到了那个规范,但是当适当的时间到来时显然忘记了它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2013-12-16
    • 2018-07-20
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    相关资源
    最近更新 更多