2013-08-29 156 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

相關問題