首页 > 解决方案 > 如何在熊猫 barh 图中仅堆叠选定的列

问题描述

我正在尝试绘制一个条形图,其中我想要两个条形图,一个堆叠,另一个未堆叠在堆叠的一侧。

我有第一个图,它是一个堆叠图:

在此处输入图像描述

另一个情节,具有相同的行和列:

在此处输入图像描述

我想将它并排绘制到最后一个图的列,而不是堆叠它:

这是复制我的问题的代码片段:

d = pd.DataFrame({'DC': {'col0': 257334.0,
  'col1': 0.0,
  'col2': 0.0,
  'col3': 186146.0,
  'col4': 0.0,
  'col5': 366431.0,
  'col6': 461.0,
  'col7': 0.0,

  'col8': 0.0},
 'DC - IDC': {'col0': 32665.0,
  'col1': 0.0,
  'col2': 156598.0,
  'col3': 0.0,
  'col4': 176170.0,
  'col5': 0.0,
  'col6': 0.0,
  'col7': 0.0,
  'col8': 0.0},
 'No Address': {'col0': 292442.0,
  'col1': 227.0,
  'col2': 298513.0,
  'col3': 117167.0,
  'col4': 249.0,
  'col5': 747753.0,
  'col6': 271976.0,
  'col7': 9640.0,
  'col8': 211410.0}})




d[['DC', 'DC - IDC']].plot.barh(stacked=True)
d[['No Address']].plot.barh( stacked=False, color='red')

标签: pythonpandasmatplotlibbar-chartstacked-chart

解决方案


使用position参数在同一索引上绘制 2 列:

fig, ax = plt.subplots()
d[['DC', 'DC - IDC']].plot.barh(width=0.4, position=0, stacked=True, ax=ax)
d[['No Address']].plot.barh(width=0.4, position=1, stacked=True, ax=ax, color='red')
plt.show()

酒吧


推荐阅读