2014-10-21 1 views
0

나는 예측 및 신뢰도 간격 데이터가있는 시계열을 가지고 있으므로 ggplot2를 사용하여 범례와 동시에 그릴 수 있습니다. 나는 아래의 코드에 의해 그 일을 해요 : 나는 전설을 포함하고 싶었다 이제ggplot2를 사용하여 범례와 시간축을 동시에 표시

ggplot(df1, aes(x = time, y = M)) + geom_line(colour='blue') + 
    geom_smooth(aes(x=time, y=M, ymax=upper, ymin=lower), 
       colour='red', data=df2, stat='identity') 

enter image description here

:

set.seed(321) 
library(ggplot2) 
#create some dummy data similar to mine 

sample<-rnorm(350) 
forecast<-rnorm(24) 
upper<-forecast+2*sd(forecast) 
lower<-forecast-2*sd(forecast) 


## wrap data into a data.frame 
df1 = data.frame(time = seq(325,350,length=26), M = sample[325:350], isin = "observations") 
df2 = data.frame(time = seq(351,374,length=24), M = forecast , isin = "my_forecast") 
df3 = data.frame(time = seq(351,374,length=24), M = upper ,isin = "upper_bound") 
df4 = data.frame(time = seq(351,374,length=24), M = lower, isin = "lower_bound") 
df = rbind(df1, df2, df3, df4) 

이전 질문 @Matthew Plourde에서 것은 나에게 좋은 대답을 제안 "관측"과 "my_forecast". 내가 함께 시도한

ggplot(df1, aes(x = time, y = M)) + geom_line(colour='blue') + 
    geom_smooth(aes(x=time, y=M, ymax=upper, ymin=lower), 
       colour='red', data=df2, stat='identity')+ scale_colour_manual(values=c(observations='blue', my_forecast='red')) 

그러나 범례를 표시하지 않습니다.

답변

2

범례를 만들려면 colour 매개 변수를 aes으로 이동해야합니다.

ggplot(df1, aes(x = time, y = M)) + geom_line(aes(colour = 'blue')) + 
    geom_smooth(aes(x = time, y = M, ymax = upper, ymin = lower, colour = 'red'), 
       data = df2, stat = 'identity') + 
    scale_colour_manual("", values = c("blue", "red"), 
         labels = c("observations", "my forecast")) 

enter image description here

관련 문제