2016-10-04 74 views
0

創建同比劇情用了一個月通過scale_x_date()x軸請看以下數據:與GGPLOT2

library(ggplot2) 
library(lubridate) 

date <- seq.Date(ymd("2015-01-01"), Sys.Date(), by = "day") 

df <- data.frame(date = date, 
       value = seq_along(date) + rnorm(length(date), sd = 100)) 

# Add yday and year 
df$yday <- yday(df$date) 
df$year <- year(df$date) 

head(df) 
#   date value yday year 
# 1 2015-01-01 97 1 2015 
# 2 2015-01-02 89 2 2015 
# 3 2015-01-03 68 3 2015 
# 4 2015-01-04 57 4 2015 
# 5 2015-01-05 70 5 2015 
# 6 2015-01-06 100 6 2016 

我想提出與顏色的「同比」的情節分配到一年。我可以用下面這樣做:

ggplot(df, aes(x = yday, y = value, color = factor(year))) + 
    geom_line() 

Plot

但是這導致了x軸是「一年中的一天」,而不是一個月的標籤。添加+ scale_x_date()失敗,因爲yday不再是日期。

是可以使用scale_x_date()

在一天結束的時候,我就喜歡做這樣的事情:

ggplot(df, aes(x = date, y = value, color = factor(year))) + 
    geom_line() + 
    scale_x_date(date_labels = "%b") 

但是要「堆積」在同積多年。

+0

我想你不想用變通的答案給你[前一個問題(http://stackoverflow.com/questions/28503262/using-lubridate-and -ggplot2有效地換日期軸)?也許澄清這個有什麼不同,否則它看起來像重複。 – aosmith

回答

3

這樣如何破解:我們不關心哪一年yday從何而來,所以只需將其轉換回Date格式(在這種情況下,今年將永遠是1970年,而不管實際一年給定yday來自何方)並僅顯示x軸標籤的月份。

您並不需要將ydayyear列添加到您的數據框中,因爲您可以在ggplot調用中實時創建它們。

ggplot(df, aes(x = as.Date(yday(date), "1970-01-01"), y = value, 
       color = factor(year(date)))) + 
    geom_line() + 
    scale_x_date(date_breaks="months", date_labels="%b") + 
    labs(x="Month",colour="") + 
    theme_bw() 

有可能是一個更乾淨的方式,並希望有人更熟練與R日期會出現並提供它。

enter image description here