gpt4 book ai didi

python - 在 python ggplot 中排序构面

转载 作者:行者123 更新时间:2023-12-01 03:12:16 25 4
gpt4 key购买 nike

我有一个数据框,df,其中print df.head()给出:

journey_time                  time_stamp    day_name  day_no  week_no
240 289 2017-03-06 00:03:58 Monday 0 10
241 288 2017-03-06 00:08:58 Monday 1 10
242 291 2017-03-06 00:13:58 Monday 1 10
243 289 2017-03-06 00:18:59 Monday 1 10
244 295 2017-03-06 00:23:58 Monday 2 10
243 289 2017-03-06 00:18:59 Monday 2 10
244 295 2017-03-06 00:23:58 Monday 2 10

我基本上每天都有一系列 journey_time 值,范围为 day_no

p = ggplot(aes(x='time_stamp',y='journey_time'),data=df) + scale_x_date(labels = date_format("%H:%M"), date_minor_breaks = "1 hour") + geom_line() + labs(x="Time", y="journey_time (seconds)") + facet_grid('day_name',scales='free_x')

这工作正常,因为我得到了 7 个水平图。然而,日期不按顺序排列(周五、周一、周六等)。如何按 day_no 记录订购?

enter image description here

最佳答案

默认情况下,ggplot 似乎按字母顺序放置分类变量,但您可以使用 category来自 Pandas 的 dtype 来指定您自己的顺序:

df.day_name = pd.Categorical(df.day_name, 
ordered=True,
categories=["Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday",
"Sunday"])

这在我的测试环境(Python 3.4、Pandas 0.18.0、ggplot 0.11.5)中按预期工作。

关于python - 在 python ggplot 中排序构面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42763667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com