按每个方面内的值计数对 seaborn catplot 进行排序

Sort seaborn catplot by value counts within each facet

我很接近,但还不够。我正在尝试按每个分组中的值计数对 sns.catplot 进行排序。

代码和输出:

fig = plt.subplots(dpi=300)
plt.figure(figsize=(10, 10))

grid = sns.catplot(data=df, kind='count', y='violation_raw', row='stop_duration', height=4, aspect=3,
                   sharey=False, palette="dark:salmon_r",
                   order=df['violation_raw'].value_counts(ascending=False).index)

ax = grid.axes[0, 0]
ax.bar_label(ax.containers[0])
ax = grid.axes[1, 0]
ax.bar_label(ax.containers[0])
ax = grid.axes[2, 0]
ax.bar_label(ax.containers[0])

plt.xlabel("Count", labelpad=12)

plt.margins(x=0.2)
plt.tight_layout()
plt.show()

它在每个分组中以完全相同的顺序列出行,但它们不按每个分组内的值计数排序。

我想按 value_counts() 每个分组中的行进行排序。

It is listing the rows in the exact same order per grouping, but they are not sorted by value counts within each grouping.

这是因为 order 当前设置为全局值计数。我不确定是否可以为每个方面设置不同的 order

一个选项是将 groupby.value_counts() 直接作为 data 传递,并使用 kind='bar':

绘制分组计数
grid = sns.catplot(
    data=df.groupby('stop_duration')['violation_raw'].value_counts().reset_index(name='violation_count'),
    kind='bar', x='violation_count', y='violation_raw', row='stop_duration',
    height=4, aspect=3, sharey=False, palette='dark:salmon_r')

for ax in grid.axes.flat:
    ax.bar_label(ax.containers[0])