【问题标题】:Seaborn: Sorting countplot by ascendingSeaborn:按升序对计数图进行排序
【发布时间】:2021-12-27 01:51:45
【问题描述】:

如何,我可以对这个图进行排序以从大到小显示吗?我尝试使用 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)

【问题讨论】:

  • 看起来它正在按字母顺序对月份进行排序。您是否尝试过创建一个以月份为整数的新列并按此排序?
  • @NickODell 哦,感谢您的想法,我应该尝试这样做。我现在正在尝试放置 .astype(int) 来更改它,但不起作用

标签: pandas matplotlib seaborn


【解决方案1】:

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

您可以使用order= 关键字或将列设置为Categorical 来设置固定顺序。

要从低到高排序,您可以使用 pandas df.groupby('...').size().sort_values().index 作为 order= 参数。使用...[::-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()

【讨论】:

    猜你喜欢
    • 2021-07-06
    • 2021-06-09
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 2019-07-23
    • 1970-01-01
    相关资源
    最近更新 更多