【问题标题】:How to create a stacked bar chart for my DataFrame using seaborn [duplicate]如何使用 seaborn 为我的 DataFrame 创建堆叠条形图 [重复]
【发布时间】:2018-04-18 16:39:50
【问题描述】:

我有一个 DataFrame df:

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]])

# display(df)
   App  Feature1  Feature2  Feature3  Feature4  Feature5  Feature6  Feature7  Feature8
0  SHA         0         0         1         1         1         0         1         0
1  LHA         1         0         1         1         0         1         1         0
2  DRA         0         0         0         0         0         0         1         0
3  FRA         1         0         1         1         1         0         1         1
4  BRU         0         0         1         0         1         0         0         0
5  PAR         0         1         1         1         1         0         1         0
6  AER         0         0         1         1         0         1         1         0
7  SHE         0         0         0         1         0         0         1         0

我想创建一个堆积条形图,以便每个堆栈对应于 App,而 Y 轴将包含 1 值的计数,而 X 轴将是 Feature

它应该类似于这个条形图,唯一的区别是现在我想查看堆栈条和带颜色的图例:

df_c = df.iloc[:, 1:].eq(1).sum().rename_axis('Feature').reset_index(name='Cou‌nt')
df_c = df_c.sort_values('Cou‌nt')
plt.figure(figsize=(12,8))
ax = sns.barplot(x="Feature", y='Cou‌nt', data=df_c, palette=sns.color_palette("GnBu", 10))
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()

【问题讨论】:

    标签: python pandas matplotlib seaborn


    【解决方案1】:

    您可以按照@Bharath 的建议使用熊猫图:

    import seaborn as sns
    sns.set()
    df.set_index('App').T.plot(kind='bar', stacked=True)
    

    输出:

    更新:

    从 matplotlib.colors 导入 ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index,axis=1)\ .T.plot(kind='bar',stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

    更新的 Pandas 0.21.0+ reindex_axis 已弃用,请使用 reindex

    from matplotlib.colors import ListedColormap
    
    df.set_index('App')\
      .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
      .T.plot(kind='bar', stacked=True,
              colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
              figsize=(12,6))
    

    输出:

    【讨论】:

    • 如果有多行具有相同的App 值,请使用groupby 而不是set_index 作为df.groupby('App').sum().T.plot(kind='bar', stacked=True)
    猜你喜欢
    • 2020-09-24
    • 2021-11-13
    • 2019-06-18
    • 2017-07-14
    • 2022-01-16
    • 2021-11-16
    • 2019-12-29
    相关资源
    最近更新 更多