You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为线性回归线上下的数据点设置不同显示颜色?

实现回归线上方与下方数据点的颜色区分

当然可以实现,核心思路是通过模型预测值和实际观测值的对比,给每个数据点标记位置(上方/下方),再根据标记设置颜色。以下是具体实现步骤:

1. 准备数据与模型

你提供的模拟数据和拟合好的线性回归模型如下:

# 模拟数据
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))

# 拟合线性回归模型
model <- lm(formula = y ~ x, data = mydata)

模型输出:

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

Coefficients:
(Intercept)            x  
     1.5770       0.8014  

2. 标记数据点位置

计算模型的预测值,然后对比实际y值和预测值,给每个点添加"回归线上方/下方"的标记:

# 计算每个x对应的预测y值
mydata$y_pred <- predict(model)

# 标记位置:实际y大于预测值则在上方,反之在下方
mydata$position <- ifelse(mydata$y > mydata$y_pred, "回归线上方", "回归线下方")

3. 绘图实现颜色区分

这里提供两种常用的绘图方式:

方式一:使用ggplot2(推荐,更美观灵活)

library(ggplot2)

ggplot(mydata, aes(x = x, y = y, color = position)) +
  geom_point(size = 3) +  # 绘制数据点,按position区分颜色
  geom_abline(intercept = coef(model)[1], slope = coef(model)[2], 
              color = "black", linetype = "dashed") +  # 添加回归线
  scale_color_manual(values = c("回归线上方" = "red", "回归线下方" = "blue")) +  # 自定义颜色
  labs(title = "回归线上下方数据点区分", x = "x", y = "y", color = "位置") +
  theme_minimal()

方式二:使用基础绘图

# 初始化空图
plot(y ~ x, data = mydata, type = "n", main = "回归线上下方数据点区分", xlab = "x", ylab = "y")

# 绘制回归线下方的点(蓝色)
points(y ~ x, data = mydata[mydata$position == "回归线下方",], col = "blue", pch = 16)
# 绘制回归线上方的点(红色)
points(y ~ x, data = mydata[mydata$position == "回归线上方",], col = "red", pch = 16)

# 添加回归线
abline(model, lty = 2, col = "black")

# 添加图例
legend("topleft", legend = c("回归线上方", "回归线下方"), 
       col = c("red", "blue"), pch = 16)

运行上述代码后,就能看到回归线上方的点和下方的点以不同颜色展示了。


内容的提问来源于stack exchange,提问作者user19598613

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 15:24:20