Seaborn:按升序排序计数图

Seaborn: Sorting countplot by ascending

如何,我可以对这个图进行排序以从大到小显示吗?我尝试使用 sort_values 但不起作用

plt.figure(figsize=(15,8))
sns.countplot(x='arrival_date_month',data=df.sort_values('arrival_date_month',ascending=False))
plt.xticks(rotation=45)

字符串类型列的默认顺序是数据框中出现的顺序。

您可以设置固定顺序,方法是使用 order= 关键字,或者将列设置为 Categorical.

要从低到高排序,可以对order=参数使用pandasdf.groupby('...').size().sort_values().index。使用 ...[::-1] 反转该顺序。

下面是一些示例代码:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

np.random.seed(2021)
sns.set()
month_names = ['January', 'February', 'March', 'April', 'May', 'June',
               'July', 'August', 'September', 'October', 'November', 'December']
df = pd.DataFrame({'arrival_date_month': np.random.choice(month_names, 1000)})

fig, axs = plt.subplots(ncols=3, figsize=(16, 3))

sns.countplot(x='arrival_date_month', data=df, ax=axs[0])
axs[0].set_title('default order (order of occurrence)')

sns.countplot(x='arrival_date_month', data=df, order=month_names, ax=axs[1])
axs[1].set_title('setting an explicit order')

large_to_small = df.groupby('arrival_date_month').size().sort_values().index[::-1]
sns.countplot(x='arrival_date_month', data=df, order=large_to_small, ax=axs[2])
axs[2].set_title('order from largest to smallest')

for ax in axs:
    ax.tick_params(axis='x', rotation=45)
plt.tight_layout()
plt.show()