将24h转换为AM / PM格式

时间:2013-08-29 11:54:08

标签: r date datetime ggplot2

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

到目前为止,我有:

ggplot

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,但由于空间原因,我只包括230。我想要的是显示1的x轴,或类似的东西。难道不能那么难吗?我尝试使用需要6am, 9am, 12am, 3pm, 6pm, 9pm, 12pm对象的scale_x_date进行实验,但我失败了,因为我不知道如何处理原点 - 几个小时内没有任何来源!

2 个答案:

答案 0 :(得分:2)

您可以根据需要使用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()

enter image description here

答案 1 :(得分:1)

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")) 

enter image description here