使用pd.DataFrame.plot()编辑条形图宽度
我正在制作一个堆叠柱状图,使用的是:
DataFrame.plot(kind='bar',stacked=True)
我想控制柱子的宽度,让它们像直方图一样相互连接。
我查阅了文档,但没有找到解决办法——有没有什么建议?这样做可能吗?
4 个回答
2
一个matplotlib的解决方案
你可以根据自己的需要调整 ax.bar
中的 width
参数。
这里有个示例图:

代码
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
df = pd.DataFrame(np.arange(15).reshape(5, 3), columns=list('ABC'))
print(df)
fig, axs = plt.subplots(1, 2)
ax = axs[0]
xs = np.arange(df.shape[1])
ys = np.zeros(xs.shape)
for ind in df.index:
ax.bar(xs, df.loc[ind, :], label=ind, bottom=ys, width=.4)
ys += df.loc[ind, :]
plt.setp(ax, xticks=xs, xticklabels=list(df))
ax.legend(title='rows')
ax.set_xlabel('columns')
ax = axs[1]
xs = np.arange(df.shape[0])
ys = np.zeros(xs.shape)
for col in list(df):
ax.bar(xs, df.loc[:, col], label=col, bottom=ys, width=.4)
ys += df.loc[:, col]
plt.setp(ax, xticks=xs, xticklabels=df.index.to_numpy().tolist())
ax.legend(title='columns')
ax.set_xlabel('rows')
plt.show()
数据框
A B C
0 0 1 2
1 3 4 5
2 6 7 8
3 9 10 11
4 12 13 14
17
如果你觉得需要用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()
106
对于看到这个问题的朋友:
从pandas 0.14版本开始,绘制条形图时可以使用一个叫'width'的命令:
https://github.com/pydata/pandas/pull/6644上面的例子现在可以简单地通过使用
df.plot(kind='bar', stacked=True, width=1)
来解决。你可以查看 pandas.DataFrame.plot.bar
或者 pandas.DataFrame.plot
,并使用 kind='bar'
来绘制条形图。
在调整条形的宽度时,可能也需要通过设置 figsize=
参数来改变图形的大小。