使用matplotlib中的dataframe.plot()函数编辑条的宽度

Osm*_*hop 30 python matplotlib histogram bar-chart pandas

我使用以下方法制作堆积条形图:

DataFrame.plot(kind='bar',stacked=True)
Run Code Online (Sandbox Code Playgroud)

我想控制条的宽度,以便条形图像直方图一样相互连接.

我查看了文档,但无济于事 - 有什么建议吗?有可能这样做吗?

小智 65

对于遇到此问题的任何人:

由于pandas 0.14,使用条形图绘制有'width'命令:https: //github.com/pydata/pandas/pull/6644

现在只需使用即可解决上述示例

df.plot(kind='bar', stacked=True, width=1)
Run Code Online (Sandbox Code Playgroud)


bmu*_*bmu 16

如果认为你必须用matplotlib"后处理"条形图,因为pandas在内部设置条形的宽度.

形成条的矩形在容器对象中.因此,您必须遍历这些容器并分别设置矩形的宽度:

In [208]: df = pd.DataFrame(np.random.random((6, 5)) * 10,               
                        index=list('abcdef'), columns=list('ABCDE'))

In [209]: df
Out[209]: 
     A    B    C    D    E
a  4.2  6.7  1.0  7.1  1.4
b  1.3  9.5  5.1  7.3  5.6
c  8.9  5.0  5.0  6.7  3.8
d  5.5  0.5  2.4  8.4  6.4
e  0.3  1.4  4.8  1.7  9.3
f  3.3  0.2  6.9  8.0  6.1

In [210]: ax = df.plot(kind='bar', stacked=True, align='center')

In [211]: for container in ax.containers:
              plt.setp(container, width=1)
   .....:         

In [212]: x0, x1 = ax.get_xlim()

In [213]: ax.set_xlim(x0 -0.5, x1 + 0.25)
Out[213]: (-0.5, 6.5)

In [214]: plt.tight_layout()
Run Code Online (Sandbox Code Playgroud)

stacked_bar.png

  • 很好的答案.我没有意识到'后处理'是一种选择 (3认同)