matplotlib 文档提供了一个解决方案。但我不太喜欢它,因为它旨在为每个酒吧设置不同的舱口。
但恕我直言,在大多数情况下,为栏的每个“类别”设置一个特定的孵化更相关。您可以通过使用影线单独绘制条形图来做到这一点,也可以在绘制后设置影线。在绘图后设置阴影更加灵活,因此这是我的方法:
df = pd.DataFrame(np.random.randint(0,20,size=(5, 2)), columns=list('AB'))
fig, ax = plt.subplots()
ax = df.sort_values('B', ascending=True).plot.barh(rot=0,ax=ax)
# get all bars in the plot
bars = ax.patches
patterns = ['/', '|'] # set hatch patterns in the correct order
hatches = [] # list for hatches in the order of the bars
for h in patterns: # loop over patterns to create bar-ordered hatches
for i in range(int(len(bars) / len(patterns))):
hatches.append(h)
for bar, hatch in zip(bars, hatches): # loop over bars and hatches to set hatches in correct order
bar.set_hatch(hatch)
# generate legend. this is important to set explicitly, otherwise no hatches will be shown!
ax.legend()
plt.show()
与单独绘制条形图相比,此解决方案的优点是:
- 你可以有任意数量的酒吧
- 适用于所有可能组合的堆叠和/或非堆叠条
- 与熊猫绘图界面一起使用
主要缺点是额外的 LOC,特别是对于仅绘制几个条形图。但是将它打包成一个函数/模块并重新使用它可以解决这个问题。:)