python - 为什么该图的底部有额外的空间?

标签 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

最佳答案

这是因为 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')

关于python - 为什么该图的底部有额外的空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23478158/

相关文章:

algorithm - 匹配两个社交媒体资料

python - 提取列表中的 Unicode 表情符号,Python 3.x

python - Pyspark 中的并发

python - PyTorch 的 grid_sample 转换为 CoreML(通过 coremltools)

python - 我怎样才能提高这个numpy循环的效率

python - 使用设置重新排列 for 循环的顺序

python - django 如何在客户端测试中设置请求用户

python - 如何从 numpy 数组中获取字符串值?

matlab - 正态概率图解释

database - 在持久存储中存储图形的最佳方法是什么