2013-08-29 154 views
-1

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

到目前为止,我有:

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,或类似的东西。不能那么难吗?我试着用scale_x_date进行试验,这需要一个Date的对象,但是我失败了,因为我不知道如何处理这个起源 - 几小时内就没有任何起源!

+0

我很抱歉,但是时间显然不是'Date's。 – Roland

+0

好吧,但使用'scale_x_date'的唯一方法是将其转换为'Date'对象,对吧?或者有什么像'scale_x_hour'? ;-) – wnstnsmth

+0

我发布了一个替代解决方案,它使用字符串代替(如果您想使用'scale_x_datetime'进行一些改进,我可以将日期解决方案返回。 –

回答

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

+0

对不起,但“14pm”之类的确显然不是存在;;)但我更喜欢你的答案,因为它不再使用更多的包。 – wnstnsmth

+0

@wnstnsmth固定。疯狂和unlogical时间格式。 – Roland

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

相关问题