2016-05-30 119 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)