R 线性趋势线上方/下方数值的不同颜色

R 线性趋势线上方/下方数值的不同颜色,r,ggplot2,R,Ggplot2,我用ggplot用线性回归线绘制时间序列。我希望我的时间序列有不同的颜色,这取决于它是高于趋势线还是低于趋势线 下面是一个代码示例,用于绘制系列和相应的趋势线,并使用系列和线的不同颜色: x <- seq(as.Date("2000/1/1"), as.Date("2010/1/1"), "years") y <- rnorm(length(x),0,10) df <- data.frame(x,y) ggplot(df, aes(x, y)) + stat_smo

我用ggplot用线性回归线绘制时间序列。我希望我的时间序列有不同的颜色,这取决于它是高于趋势线还是低于趋势线

下面是一个代码示例,用于绘制系列和相应的趋势线,并使用系列和线的不同颜色:

x  <- seq(as.Date("2000/1/1"), as.Date("2010/1/1"), "years")
y  <- rnorm(length(x),0,10)
df <- data.frame(x,y)

ggplot(df, aes(x, y)) + 
  stat_smooth(method = 'lm', aes(colour = 'Trend'), se = FALSE) +
  geom_line(aes(colour = 'Observation') ) +   
  theme_bw() + 
  xlab("x") + 
  ylab("y") + 
  scale_colour_manual(values = c("blue","red"))

x我扔掉了枣子,因为它们快把我逼疯了。也许有人可以为这个问题添加一个解决方案。否则,通过一些基础的高中数学,这似乎是可行的

df <- data.frame(x = 2000:2010,
                 y = rnorm(11, 0, 10))
fm <- lm(y ~ x, data = df)
co <- coef(fm)
df$under_over <- sign(fm$residuals)
for (i in 1:(nrow(df) - 1)) {
  # Get slope and intercept for line segment
  slope <- (df$y[i + 1] - df$y[i]) / (df$x[i + 1] - df$x[i])
  int  <- df$y[i] - slope * df$x[i]
  # find where they would cross
  x <- (co[1] - int) / (slope - co[2])
  y <- slope * x + int
  # if that is in the range of the segment it is a crossing, add to the data
  if (x > df$x[i] & x < df$x[i + 1])
    df <- rbind(df, c(x = x, y = y, under_over = NA))
}
#order by x
df <- df[order(df$x), ]
# find color for intersections
for (i in 1:nrow(df))
  if (is.na(df$under_over[i]))
    df$under_over[i] <- df$under_over[i + 1]

ggplot(df) +
  geom_abline(intercept = co[1], slope = co[2]) +
  geom_path(aes(x, y, col = as.factor(under_over), group = 1)) +
  theme_bw()

df有些关联:估计回归,然后使用模型中的残差(
符号(model$residuals)
)作为变量来生成颜色。感谢您的提示!我想了想。这种方法的问题是,当一个点位于趋势线上方,而另一个点位于趋势线下方时,时间序列各点之间的连接将具有错误的颜色。如果你真的需要为你的时间序列绘制一条线,我认为你必须先计算回归,添加时间序列穿过趋势线的点,然后使用@Thomas的建议。(并使用
group=1