【问题标题】:How to sort bars in increasing order in a bar chart? [duplicate]如何在条形图中按升序对条形进行排序? [复制]
【发布时间】:2018-04-18 16:09:04
【问题描述】:

我有一个 DataFrame df,我使用下面显示的代码将其转换为 df_c

df = pd.DataFrame(columns=["App","Feature1", "Feature2","Feature3",
                           "Feature4","Feature5",
                           "Feature6","Feature7","Feature8"], 
                  data=[["SHA",0,0,1,1,1,0,1,0],
                        ["LHA",1,0,1,1,0,1,1,0],
                        ["DRA",0,0,0,0,0,0,1,0],
                        ["FRA",1,0,1,1,1,0,1,1],
                        ["BRU",0,0,1,0,1,0,0,0],
                        ["PAR",0,1,1,1,1,0,1,0],
                        ["AER",0,0,1,1,0,1,1,0],
                        ["SHE",0,0,0,1,0,0,1,0]])
df_c = df.iloc[:, 1:].eq(1).sum().rename_axis('Feature').reset_index(name='Cou‌​nt')

然后我使用 matplotlib 和 seaborn 创建一个条形图:

plt.figure(figsize=(12,8))
ax = sns.barplot(x="Feature", y="Count", data=df_c, palette=sns.color_palette("GnBu", 10), order=df_c['Feature'])
plt.xticks(rotation='vertical')
ax.grid(b=True, which='major', color='#d3d3d3', linewidth=1.0)
ax.grid(b=True, which='minor', color='#d3d3d3', linewidth=0.5)
plt.show()

我想按从左到右的升序对条形图进行排序。如果我这样做order=df_c['Count'],条就会消失。

【问题讨论】:

    标签: python pandas matplotlib seaborn


    【解决方案1】:

    最简单的方法是在绘图前进行排序:

    df_c = df_c.sort_values('Count')
    

    【讨论】:

      猜你喜欢
      • 2017-12-06
      • 1970-01-01
      • 2021-07-06
      • 2014-10-02
      • 2022-08-23
      • 2020-09-01
      • 2014-05-03
      • 2021-10-10
      • 2017-09-09
      相关资源
      最近更新 更多