2016-05-30 92 views
0

假設我有一個數據框如下,並做了一個ggplot與我的數據的最後幾個時期的線性線,我想知道是否有可能應用不同的顏色的geom_smooth線基於其梯度(例如綠色if其上升趨勢,如果趨勢下跌趨勢和黑色趨勢大致不變,則爲紅色)?如何根據漸變採用不同顏色的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)