pandas 使用 groupby 对图中的值进行排序

pandas sort values in plot with groupby

我正在处理这个数据集,我有下面的绘图代码

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)

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

你可以做到,但可能需要分别绘制每个子图。

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。对我来说,最好是有原始图表而不是像这样的图表(跟踪组之间的差异要容易得多)。