【问题标题】:pandas sort x axis with categorical string valuespandas 使用分类字符串值对 x 轴进行排序
【发布时间】:2020-03-25 22:34:31
【问题描述】:

我正在尝试对熊猫图 x 轴中的分类变量进行排序。我尝试从熊猫数据框本身进行排序,但我只能按字母顺序排序。我在情节中看不到以这种方式对其进行排序的选项。 我正在尝试按以下顺序获取 x 轴: [Mon, Tue, Wed, Thru, Fri, Sat, Sun] 。我该怎么做?

df = data_df.groupby(['name1','weekday']).sum().reset_index()
s = (df.pivot_table(
        index='weekday', columns='name1', values='count', aggfunc='sum'))

s.plot(kind='bar', stacked=True,figsize=(20,10),rot=0)
plt.show()

寻找这个输出

【问题讨论】:

  • 这能回答你的问题吗? sorting by a custom list in pandas
  • @Alan 不,实际上。它没有用。我正在尝试查看 pandas 数据框图是否可以进行自定义排序。
  • 请提供您正在使用的数据。谢谢。

标签: python-3.x pandas plotly


【解决方案1】:

据我所知,您的dfs 基本相同。另外,你可以reindex然后绘图:

weekdays = ['Monday','Tuesday','Wednesday','Thursday',
            'Friday','Saturday','Sunday']
# sample data
np.random.seed(1)
data_df = pd.DataFrame({
    'name1':np.random.randint(0,3, 100),
    'weekday':np.random.choice(weekdays, 100),
    'count':np.random.randint(3,100)
})

# groupby and take sum
s = (data_df.groupby(['name1','weekday'])
       .sum().unstack('name1')
       .reindex(weekdays)                 # here is the key to get the correct order
)

# plot
s.plot.bar(stacked=True)

输出:

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 2021-02-22
    • 2022-01-01
    • 2021-10-13
    • 2020-05-19
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 2011-01-14
    相关资源
    最近更新 更多