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

如何构建两向量线性关系?用plot_ly绘相关图并加回归线、算R²

嘿,我来帮你搞定这个问题!用plotly给散点图加回归线和R²其实没那么复杂,我给你拆解两种可行的方法,还有可能的报错排查思路~

方法一:纯plot_ly原生实现

这种方法直接用plot_ly的语法,先拟合线性模型,再叠加回归线和R²标注。

1. 准备数据并拟合线性回归

首先我们需要先对数据做线性回归,提取回归系数和R²值:

library(plotly)
library(dplyr)

# 模拟你的数据(替换成你自己的真实数据即可)
set.seed(123)
x <- rnorm(50, mean = 10, sd = 2)
y <- 2*x + rnorm(50, mean = 0, sd = 3)
df <- data.frame(x, y)

# 拟合线性回归模型
lm_model <- lm(y ~ x, data = df)
# 提取回归系数(可选,用来显示回归方程)
reg_eq <- paste0("y = ", round(coef(lm_model)[2], 2), "x + ", round(coef(lm_model)[1], 2))
# 计算并格式化R²值
r_squared <- paste0("R² = ", round(summary(lm_model)$r.squared, 2))

2. 绘制散点图+回归线+标注

接下来用plot_ly绘制散点,叠加回归线,再把R²(甚至回归方程)放到图上:

# 初始化散点图
p <- plot_ly(df, x = ~x, y = ~y, 
             type = 'scatter', mode = 'markers', 
             name = '原始数据点', marker = list(color = '#1f77b4')) %>%
  # 添加回归线:用模型预测的y值生成线条
  add_trace(x = ~x, y = predict(lm_model),
            type = 'scatter', mode = 'lines',
            name = '回归线', line = list(color = '#ff7f0e', width = 2)) %>%
  # 添加注释:把回归方程和R²放在图的右上角
  layout(annotations = list(
    list(x = max(df$x), y = max(df$y),
         text = paste(reg_eq, r_squared, sep = "<br>"),
         showarrow = FALSE,
         xanchor = 'right', yanchor = 'top',
         font = list(size = 12)),
    ),
    xaxis = list(title = 'X变量'),
    yaxis = list(title = 'Y变量'),
    title = '散点图与线性回归线')

# 显示图形
p

常见报错排查

你之前出现报错,大概率是这几个原因:

  • 没有先拟合线性模型就直接尝试添加回归线,导致predict()找不到对应模型;
  • 数据格式问题:plot_ly对数据框格式更友好,如果你的数据是向量,建议先转成data.frame;
  • 注释位置设置不合理:如果x或y的取值超出了当前轴的范围,注释会被隐藏,可以调整x和y的取值(比如用quantile(df$x, 0.9)代替max(df$x))。
方法二:用ggplot2+plotly转换(更省心)

如果你更熟悉ggplot2的语法,也可以先用ggplot2画好带回归线和R²的图,再转换成plotly交互图,步骤更简单:

首先需要安装ggpmisc包来自动生成回归方程和R²:

install.packages("ggpmisc")

然后绘图并转换:

library(ggplot2)
library(plotly)
library(ggpmisc)

# 用ggplot2绘制带回归线和R²的图
gg_plot <- ggplot(df, aes(x = x, y = y)) +
  geom_point(color = '#1f77b4') +
  # 添加回归线(se=FALSE去掉置信区间)
  geom_smooth(method = 'lm', se = FALSE, color = '#ff7f0e', linewidth = 1) +
  # 自动添加回归方程和R²
  stat_poly_eq(formula = y ~ x, 
               aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
               parse = TRUE, label.x = "right", label.y = "top", size = 4) +
  labs(x = 'X变量', y = 'Y变量', title = '散点图与线性回归线')

# 转换成plotly交互图
ggplotly(gg_plot)

这种方法不需要手动计算R²和回归方程,stat_poly_eq会自动帮你生成,而且ggplot2的语法更直观,转换后的plotly图依然保留交互性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:28:33