【问题标题】:How to Sort Seaborn barplot in ascending or descending order [duplicate]如何按升序或降序对Seaborn条形图进行排序[重复]
【发布时间】:2021-07-06 07:25:26
【问题描述】:

EXCEL文件有7000苹果应用商店的信息,如下图

这是我的代码 ->

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd 
apple_store_data = pd.read_excel(r'apple_store.xlsx')
sns.barplot(data=apple_store_data,y='PrimaryGenre',x='AvgRating',color='g')
plt.show()

它会给出这样的输出 ->

【问题讨论】:

  • 希望答案是有帮助的。彻底回答问题很费时间。如果您的问题已解决,请接受解决方案 位于答案左上角的 ▲/▼ 箭头下方。如果出现更好的解决方案,则可以接受新的解决方案。如果您的声望超过 15,您还可以使用 ▲/▼ 箭头对答案的有用性进行投票。 如果解决方案无法回答问题,请发表评论。 What should I do when someone answers my question?。谢谢。

标签: python pandas seaborn data-visualization


【解决方案1】:

要按字母顺序排列条形,您可以将列 categorical 设为 ordered=True

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

df = pd.DataFrame({'Genre': np.random.choice(['helium', 'neon', 'argon', 'krypton', 'xenon', 'radon', 'oganesson'], 50),
                   'Rating': np.random.randint(1, 11, 50)})
df['Genre'] = pd.Categorical(df['Genre'], ordered=True)
ax = sns.barplot(data=df, y='Genre', x='Rating', palette='husl')
ax.tick_params(axis='y', length=0)
plt.tight_layout()
plt.show()

要按降序排列条形,您可以使用以下代码。在这种情况下,不需要将列设为分类。

ax = sns.barplot(data=df, y='Genre', x='Rating', palette='plasma',
                 order=df.groupby('Genre')['Rating'].agg('mean').sort_values(ascending=False).index)

PS:仅显示例如前5名,使用... .index[:5]

ax = sns.barplot(data=df, y='Genre', x='Rating', palette='plasma',
                 order=df.groupby('Genre')['Rating'].agg('mean').sort_values(ascending=False).index[:5])

【讨论】:

  • 如果这回答了你的问题,你可以考虑投票和/或accepting答案。
猜你喜欢
  • 2021-06-09
  • 2018-04-18
  • 2017-12-06
  • 2021-10-10
  • 1970-01-01
  • 2018-05-03
  • 2021-12-27
  • 1970-01-01
  • 2017-06-10
相关资源
最近更新 更多