2016-03-01 152 views
0

我想重現情節:如何繪製按月份和日期平均的數據?

link

link

我幾乎能做到這一點,但我錯過了什麼:

library(lubridate) 
library(ggplot2) 
# get the data 
dates <- seq(as.Date("2012-01-01"), as.Date("2014-12-30"), by = 1) 
series <- seq(from = 1, to = 1095, by = 1) 
df<-data.frame(dates,series) 

# for aggregation 
df$month<-as.numeric(format(df$date, "%m")) 
df$week<-week(as.POSIXct(df$date)) 
df$weekday<-weekdays(as.POSIXct(df$date)) 
df$days<-as.numeric(format(df$date, "%d")) 
df$week_days<-as.numeric(format(df$date, "%w")) 

# for plotting 
for_plot=aggregate(series ~ + weekday+ month, data =df, FUN=mean) 


ggplot(for_plot, aes(x=weekday, y=series)) + geom_line(aes(group=month, color=month),size=2,alpha=0.5) 

enter image description here

+0

plo如果你想精確地複製它,你應該從'plot()'函數開始,也許使用'lines()'和'points()'的組合。否則,你試圖複製的論文中的情節的哪些方面? –

回答

2

你非常接近! 只需兩到for_plotclass變化不大:

變化個月至因素得到每月

for_plot$month = as.factor(for_plot$month) 

一種顏色作爲平日character ggplot默認試圖將其排序爲字符。要防止這個轉動工作日factor並指定級別。

for_plot$weekday = factor(for_plot$weekday, 
     levels = c("Monday", "Thursday", "Tuesday", "Wednesday", "Friday", "Saturday", "Sunday")) 

當您用德語語言環境R您已經做的做,在德國,所以levels=c("Montag",...,"Sonntag")

要得到就行了點只是添加geom_point如下:

ggplot(for_plot, aes(weekday, series, group=month, col=month)) + 
    geom_line() + 
    geom_point() 

這給你

enter image description here

+0

希望不要打擾你太多,但是有沒有我的方式,一個快捷方式,只爲2013年而不是整個時期產生相同的情節?謝謝! – Mamba

+0

你可以做'df_2013 < - df [year(df $ dates)== 2013]'然後聚合'df_2013' – Rentrop

相關問題