【问题标题】:pandas sort values in plot with groupbypandas 使用 groupby 对图中的值进行排序
【发布时间】:2022-01-08 14:44:50
【问题描述】:

我正在处理这个数据集,我已经为下面的图准备了这段代码

x = df2.groupby(by = ['LearnCode', 'Age']).size()
chart = x.unstack()
axs = chart.plot.barh(subplots=True,figsize=(20,50), layout=(9,1), legend=False, title=chart.columns.tolist())
ax_flat = axs.flatten()
for ax in ax_flat:
    ax.yaxis.label.set_visible(False)

如何单独对每个图的每个类别的值进行排序?

【问题讨论】:

    标签: pandas matplotlib plot data-analysis


    【解决方案1】:

    你可以这样做,但可能你必须单独绘制每个子图。

    df2 = pd.DataFrame({'LearnCode': ['A', 'B', 'B', 'B', 'B', 'A', 'C', 'C', 'B', 'A', 'C', 'C', 'B'],
                         'Age': [18, 18, 18, 18, 18, 18, 18, 24, 24, 24, 24, 24, 24]})
    
    x = df2.groupby(by = ['LearnCode', 'Age']).size()
    chart = x.unstack()
    
    f, axs = plt.subplots(nrows=len(chart.columns), ncols=1, figsize=(20,10), sharex='col')
    #to each subplot to have different color
    colors = plt.rcParams["axes.prop_cycle"]()
    for i, age in enumerate(chart):
        chart[age].sort_values().plot.barh(title = age, 
                                           ax = axs[i], 
                                           color = next(colors)["color"],
                                           xlabel = '')
    

    PS。对我来说,最好有原始图表而不是这样的图表(跟踪组之间的差异要容易得多)。

    【讨论】:

      猜你喜欢
      • 2020-02-22
      • 2016-11-04
      • 2021-08-27
      • 2019-06-27
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      • 2015-09-16
      • 1970-01-01
      相关资源
      最近更新 更多