matplotlib条形图间距无法正常工作

2024-04-24 09:01:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用matplotlib和pandas DataFrame绘制条形图,如下所示:

pdata = pd.DataFrame([[11.14285714,  6.33333333,  2.52380952],
       [10.47619048,  6.61904762,  2.9047619 ],
       [10.80952381,  6.19047619,  3.        ],
       [11.0952381 ,  6.66666667,  2.23809524],
       [10.14285714,  4.9047619 ,  4.95238095],
       [ 9.61904762,  5.71428571,  4.66666667],
       [10.0952381 ,  5.14285714,  4.76190476],
       [ 9.47619048,  5.14285714,  5.38095238],
       [10.66666667,  4.38095238,  4.95238095],
       [ 9.66666667,  5.04761905,  5.28571429],
       [10.33333333,  4.95238095,  4.71428571],
       [10.85714286,  4.9047619 ,  4.23809524],
       [ 9.71428571,  4.9047619 ,  5.38095238],
       [10.71428571,  4.52380952,  4.76190476],
       [ 9.57142857,  3.71428571,  6.71428571],
       [11.61904762,  5.47619048,  2.9047619 ],
       [12.23809524,  5.23809524,  2.52380952],
       [11.28571429,  7.28571429,  1.42857143],
       [10.52380952,  6.52380952,  2.95238095],
       [10.80952381,  6.38095238,  2.80952381],
       [10.95238095,  7.71428571,  1.33333333],
       [11.0952381 ,  7.42857143,  1.47619048],
       [10.0952381 ,  8.71428571,  1.19047619],
       [10.42857143,  8.42857143,  1.14285714],
       [10.57142857,  7.95238095,  1.47619048],
       [10.14285714,  8.66666667,  1.19047619],
       [ 9.38095238,  9.38095238,  1.23809524],
       [ 8.9047619 ,  9.80952381,  1.28571429],
       [10.66666667,  8.04761905,  1.28571429],
       [ 9.19047619,  9.19047619,  1.61904762]])
pdata.index = np.arange(30)+1

fig,axes = plt.subplots(1,2,figsize=(6,3),sharey=True)
ax = axes[0]
pdata[pdata.index<=15].plot(
    ax=ax,kind='bar',stacked=True,width=.95, color=colors,alpha=.7, rot=0)

ax = axes[1]
pdata[pdata.index>15].plot(
    ax=ax,kind='bar',stacked=True, color=colors,width=.95,alpha=.7, rot=0)
ax.get_legend().remove()
ax.set_ylim([0,20])
fig.tight_layout()

但是,结果图如下图所示,条形图之间的间距不同:

enter image description here

有没有办法纠正间距?还有,有没有可能进一步缩小两个地块之间的距离?在


Tags: truedataframeindexplotfigbaraxwidth
1条回答
网友
1楼 · 发布于 2024-04-24 09:01:15

您看到的是两种效果的组合,width属性设置为0.95,而{}太低,无法解析条之间的每一个空格。如果您想要一些空白,但是在每个条之间,您可以简单地增加图的dpi,如注释和this answer所示

fig,axes = plt.subplots(1,2,figsize=(6,3),sharey=True, dpi=300)

将把图形的dpi设置为300,并生成如下内容

300 DPI plot with 0.95 width bars

其中条间空白是由width=0.95创建的,如果不希望条之间有任何空格,只需将width=1.0设置为生成

300 DPI plot with 1.0 width bars

请注意,在这两种情况下,我都使用了plt.subplots_adjust(wspace=0.05),而不是{},但这是一个偏好问题。此外,请注意,如果使用width=1.0,则无需调整dpi属性,因为显示将是正确的:

完整示例

^{pr2}$

相关问题 更多 >