本文介绍了线性趋势线上方/下方的值使用不同的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ggplot绘制带有线性回归线的时间序列.我希望时间序列具有不同的颜色,具体取决于它在趋势线之上还是之下.

I'm using ggplot to plot a time series with a linear regression line. I would like to have different colours for my time series depending on whether it is above or below the trend line.

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

Here is a code example to plot the series and the corresponding trend line with different colours for the series and the line:

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"))

祝你有美好的一天!

推荐答案

我摆脱了约会,因为他们让我发疯.也许有人可以为此添加解决方案.否则,通过一些基本的高中数学,这似乎是可行的.

I got rid of the dates, since they were driving me nuts. Perhaps someone can add a solution for that. Otherwise it seems quite doable, with some basic high school maths.

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()

这篇关于线性趋势线上方/下方的值使用不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 15:31