【问题标题】:Convert 24h to AM/PM format将 24 小时制转换为 AM/PM 格式
【发布时间】:2013-08-29 11:54:07
【问题描述】:

我有一个数字变量,要绘制在 x 轴上,包含从 0 到 23 的数字。我 a) 需要将这些时间转换为 Date 对象,以便在 ggplot 中可视化它们,并且我 b) 想让 x 轴以 am/pm 格式显示这些数字。

到目前为止我有:

library("ggplot2")
library(scales)
Sys.setlocale(category = "LC_ALL", locale = "English")
# data
hod <- structure(list(h = c(0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L), 
t = c(NA, 2L, 4L, 1L, 3L, NA, 2L, 4L, 1L, 3L), n = c(226L, 
226L, 226L, 226L, 226L, 226L, 226L, 226L, 226L, 226L), mean = c(4.52654867256637, 
33.6769911504425, 6.34513274336283, 30.3672566371681, 0.309734513274336, 
2.84513274336283, 20.0088495575221, 3.38938053097345, 17.7787610619469, 
0.101769911504425), std = c(2.74131025125736, 13.4781731703065, 
3.0316031901839, 10.9165210711549, 0.603524251739029, 2.25142987605743, 
10.9354466064168, 2.27892859595505, 8.76056582129717, 0.33032092222724
)), .Names = c("h", "t", "n", "mean", "std"), row.names = c(NA, 
10L), class = "data.frame")



ggplot(hod, aes(x=h, y=mean, colour=as.factor(t))) + 
geom_line(size = .1) +
geom_point() +
theme_minimal()

hod$h 实际上会一直持续到23,但由于空间原因,我只包括了01。我想要的是 x 轴显示6am, 9am, 12am, 3pm, 6pm, 9pm, 12pm,或类似的东西。不能这么难吧?我尝试使用需要Date 对象的scale_x_date 进行试验,但我失败了,因为我不知道如何处理原点——只有几个小时没有任何原点!

【问题讨论】:

  • 对不起,时间显然不是Dates。
  • 好的,但使用scale_x_date 的唯一方法是将其转换为Date 对象,对吗?还是有类似 scale_x_hour 的东西? ;-)
  • 我发布了一个使用字符串的替代解决方案(如果您想使用 scale_x_datetime 并进行一些改进,我可以将日期解决方案放回去。

标签: r date datetime ggplot2


【解决方案1】:

您可以根据需要使用strftime 来格式化时间,并将其用作x 美学。然后,您还必须使用分组美学。我们使用lubridate 来简化工作时间。试试这个:

require(lubridate)    
hod$time <- tolower( strftime( Sys.Date()+hours(hod$h) , "%I %p" ) )
# [1] "12 am" "12 am" "12 am" "12 am" "12 am" "01 am" "01 am" "01 am" "01 am" "01 am"

ggplot(hod, aes( x = time , y=mean, colour=as.factor(t) , group = t ) ) + 
geom_line(size = .1) +
geom_point()

【讨论】:

    【解决方案2】:
    ggplot(hod, aes( x = h , y=mean, colour=as.factor(t))) + 
      geom_line(size = .1) +
      geom_point() +
      scale_x_continuous(limits=c(0,24),
                         breaks=0:12*2,
                         labels=c(paste(0:5*2,"am"),
                                  "12 pm",
                                  paste(7:11*2-12,"pm"), 
                                  "0 am")) 
    

    【讨论】:

    • 对不起,“14pm”之类的显然不存在。 ;-) 我仍然更喜欢你的答案而不是上面那个,因为它不再使用任何包。
    猜你喜欢
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 2013-06-10
    • 2013-06-02
    相关资源
    最近更新 更多