【问题标题】:Display data points above/below a regression line in different colors以不同颜色显示回归线上方/下方的数据点
【发布时间】:2022-07-23 02:10:43
【问题描述】:

我为我的模拟数据拟合了一个线性回归模型:

Call:
lm(formula = y ~ x, data = mydata)

Coefficients:
(Intercept)            x  
     1.5770       0.8014  

我想知道是否有办法以不同的颜色显示回归线上方和下方的数据点。

mydata <- structure(list(x = 1:10, y = c(3.28883727809953, 2.46416802959371, 
5.21809941024356, 4.05952314018145, 5.32088305796252, 5.37511676113549, 
7.13585900360674, 7.93915982555469, 7.61133858936195, 11.4349438464509
)), class = \"data.frame\", row.names = c(NA, -10L))

    标签: r plot colors linear-regression lm


    【解决方案1】:

    这是一个演示:

    ## fit regression line
    fit <- lm(y ~ x, data = mydata)
    ## above the line (observed > fitted is TRUE): TRUE + 1 is 2, select "green"
    ## below the line (observed > fitted is FALSE): FALSE + 1 is 1, select "red"
    ptcol <- c("red", "green")[(mydata$y > fit$fitted.values) + 1]
    ## plot observed data points
    with(mydata, plot(x, y, col = ptcol))
    ## add regression line
    abline(fit)
    

    【讨论】:

      猜你喜欢
      • 2020-10-16
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 2021-06-23
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多