2016-05-30 6 views
0

データフレームが次のようになっており、データの最後の数ピリオドの線でggplotを実行したと仮定して、グラデーションに基づいてgeom_smoothラインに別の色を適用できるかどうかを知りました上向き傾向、下向き傾向、黒色傾向がほぼ一定)グラデーションに基づいてgeom_smoothラインの色を変える方法は?

Date <- as.yearqtr(seq(as.Date("2005/1/1"), as.Date("2016/1/1"), by = "quarter")) 
GDP<- as.vector(sample(1000:4000,length(Date), replace=T)) 
df <- data.frame(Date, GDP) 
ggplot(df, aes(Date, GDP)) + geom_line(colour="darkblue") + 
    geom_smooth(data=subset(df, Date >= as.numeric(df$Date[length(Date)-8])), method="lm") + 
    xlab("Date") + ylab("GDP") + ggtitle("Nominal GDP") 

答えて

0

おそらくこれに答えるのに最適な人ではありません。しかし、もし私があなたのデータにlmを実行し、(ライン傾斜である)coeffecientsを抽出し、データとしてカラムに入れるなら、それは簡単であるはずです。

model <- lm(y~x, df) ## You'll have to run your lm here. 
model$coeffecients ## Can be used to extract the slope of each line. 

あなたはそれをfigreした後、このような何かが私には理にかなって:

ggplot(df, aes(Date, GDP)) + 
geom_line(colour = "darkblue") + 
geom_smooth((data=subset(df, Date >= as.numeric(df$Date[length(Date)-8])), 
      method="lm", 
      colour = coefficient) + 
scale_fill_gradient2(high = "green", 
        low = "red", 
        mid = "black", 
        midpoint = 0) 
関連する問題