如何在RStudio中按照从早到晚的顺序绘制AM/PM时间

ogq8wdun  于 2023-02-06  发布在  其他
关注(0)|答案(1)|浏览(117)

我有以下 Dataframe :

head(CaloriesNew1)
# A tibble: 6 × 4
          id activitydate activityhourampm calories
       <dbl> <chr>        <chr>               <dbl>
1 1503960366 4/12/2016    12:00:00 AM            81
2 1503960366 4/12/2016    1:00:00 AM             61
3 1503960366 4/12/2016    2:00:00 AM             59
4 1503960366 4/12/2016    3:00:00 AM             47
5 1503960366 4/12/2016    4:00:00 AM             48
6 1503960366 4/12/2016    5:00:00 AM             48

当我绘制这个图时,它并没有将x轴从最早时间(12am)排列到最晚时间(11pm),而是按照升序(1am、1pm、10am、10pm、11am、11pm等)绘制数据。
我是这样写的:

CaloriesNew1 %>% 
  ggplot(data = CaloriesNew1, mapping = aes(x = activityhourampm, y = calories))+
  geom_point()+
  theme(axis.text.x=element_text(angle=45))

如何绘制此图,使x轴从12am、1am、2am、3am开始....................................................................................................................................................................................................................................
这是我的图表现在的样子:

carvr3hs

carvr3hs1#

我不知道如何获得12小时的时钟。有了这个,你的数据至少是根据时间排序的。

library(lubridate)
library(tidyverse)

# Read in data. I added a few lines to get PM hours.
df1 <- read.delim("clipboard", sep=" ")

df1
 x         id activitydate activityhourampm calories
 1 1503960366   2016-04-12         00:00:00       81
 2 1503960366   2016-04-12         01:00:00       61
 3 1503960366   2016-04-12         02:00:00       59
 4 1503960366   2016-04-12         03:00:00       47
 5 1503960366   2016-04-12         04:00:00       48
 6 1503960366   2016-04-12         05:00:00       48
 7 1503960366   2016-04-12         12:00:00       78
 8 1503960366   2016-04-12         14:00:00       88
 9 1503960366   2016-04-12         16:00:00       68
10 1503960366   2016-04-12         18:00:00       58
11 1503960366   2016-04-12         19:00:00       88
12 1503960366   2016-04-12         21:00:00       98

# Parse the date and time.
df1$activitydate <- parse_date(df1$activitydate, "%m/%d/%Y")
df1$activityhourampm <- parse_time(df1$activityhourampm, '%H:%M:%S %p')

# A plot like yours
df1 %>% 
  ggplot(data = df1, mapping = aes(x = activityhourampm, y = calories))+
  geom_point()+
  theme(axis.text.x=element_text(angle=45))

相关问题