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

R语言Plotly如何按颜色分组为每个类别添加单独回归线

问题原因

现有代码仅对全量数据拟合了全局一元线性回归模型,add_lines图层未关联continent分组映射规则,因此仅能生成单条全局拟合线,无法匹配散点的分组颜色逻辑,无法对应每个大洲的数据分布趋势。

实现方法

两种可直接运行的实现方案,均能按continent分组为每个大洲单独生成对应颜色的回归拟合线:

  • 方法1:原生自动拟合(代码最简洁,无需提前预处理数据)
    直接在图层内按分组拟合模型,自动继承上层的颜色映射规则,无需额外手动处理拟合值:
    library(plotly)
    library(dplyr)
    
    fig2 <- plot_ly(rugby_data, x = ~height_cm, y = ~weight_kg, 
                    type="scatter", mode="markers", color = ~continent) %>% 
      add_trace(type = "scatter", mode = "lines",
                y = ~fitted(lm(weight_kg ~ height_cm, data = pick(everything()) |> group_by(continent))),
                showlegend = FALSE) %>%
      layout(title = 'Height Vs. Weight Scatter Plot', plot_bgcolor = "#e5ecf6")
    
    fig2
    
  • 方法2:提前预处理拟合值(灵活度更高,适合自定义模型场景)
    先按分组计算好每个样本对应的拟合值,再传入线图层,支持自定义模型形式、拟合值范围等参数:
    library(plotly)
    library(dplyr)
    
    # 按大洲分组计算拟合值
    rugby_data_with_fit <- rugby_data %>%
      group_by(continent) %>%
      mutate(fit_weight = fitted(lm(weight_kg ~ height_cm))) %>%
      ungroup()
    
    fig2 <- plot_ly(rugby_data, x = ~height_cm, y = ~weight_kg, 
                    type="scatter", mode="markers", color = ~continent) %>% 
      add_lines(data = rugby_data_with_fit, x = ~height_cm, y = ~fit_weight,
                color = ~continent, showlegend = FALSE) %>%
      layout(title = 'Height Vs. Weight Scatter Plot', plot_bgcolor = "#e5ecf6")
    
    fig2
    
避坑提示
  • 图层内映射变量不要使用数据框$变量名的写法(例如不要写color = rugby_data$continent),直接用~变量名即可,否则会破坏分组映射逻辑
  • 拟合线图层的color映射变量需要和散点层保持一致,才能保证同组散点和拟合线颜色匹配
  • 如果需要在图例中单独展示拟合线条目,将showlegend参数设置为TRUE即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 07:09:27