【问题标题】:How to plot barchat with multiple bars with seaborn如何使用 seaborn 绘制带有多个条形的 barchat
【发布时间】:2020-11-13 04:13:43
【问题描述】:

我想用数据绘制条形图无法弄清楚如何用 seaborn 条形图绘制多个条形图(即我想要在 x ax 'referee_id' 和 3 条形图上每个显示赢/平/输,y ax - 数量)与这样的 DataFrame:

使用 sns.barplot() 绘图时,它会堆叠/分层所有数量。

我的代码:

figure = plt.figure(figsize=(14,6))
subplot = figure.add_subplot()
sns.barplot(all_referees['Field_referee_id'],all_referees['Quantity_lost'],  color="tomato", label = "lost")
sns.barplot(all_referees['Field_referee_id'],all_referees['Quantity_draw'],  color="yellow", label = "draw")
sns.barplot(all_referees['Field_referee_id'],all_referees['Quantity_won'],  color="limegreen", label = "won")
for item in subplot.get_xticklabels():
    item.set_rotation(45)
plt.xticks(ha='right',fontweight='light',fontsize='large')
plt.legend(loc='upper right', frameon=False)

此外:

  • 如何设置条件以仅显示裁判至少 7 场比赛(输+平+赢 >=7)的裁判?
  • 如何让每个裁判的三杆之间的宽度差距?

【问题讨论】:

    标签: python pandas bar-chart seaborn


    【解决方案1】:

    您首先需要将您的数据框从宽调整为长。

    例子:

    df = pd.DataFrame({'ID': list('abcd'), 'Quantity_Lost':[3,5,3,4], 'Quantity_Draw':[2,2,1,None], 'Quantity_Won': [5,1,4,2]})
    #  ID  Quantity_Lost  Quantity_Draw  Quantity_Won
    #0  a              3            2.0             5
    #1  b              5            2.0             1
    #2  c              3            1.0             4
    #3  d              4            NaN             2
    df1 = df[df.filter(regex='Quantity_').sum(axis=1).ge(7)]
    df1 = pd.wide_to_long(df1, stubnames=['Quantity'], i='ID', j='Result', sep='_', suffix='.*')
    sns.barplot(x='ID', y='Quantity', hue='Result', data=df1.reset_index(), palette=['tomato','yellow','limegreen'])
    


    不过,使用 pandas 进行绘图要容易得多:

    df[df.filter(regex='Quantity_').sum(axis=1).ge(7)].plot.bar(color=['tomato','yellow','limegreen'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-29
      • 2021-07-28
      • 2021-04-26
      • 1970-01-01
      • 2021-05-04
      • 2023-01-20
      • 2019-05-29
      • 2021-06-18
      相关资源
      最近更新 更多