Plotly - 如何使用 R 为每种颜色添加多重回归?

Plotly - how to add multiple regressions for each color using R?

我的绘图将所有回归线堆叠在一起。


mod = lm(weight_kg ~ height_cm, data=rugby_data) 

fig2 <- plot_ly(rugby_data, x = ~height_cm, y = ~weight_kg, type="scatter", mode="markers", color = rugby_data$continent) %>% 
        add_lines(x = rugby_data$height_cm,y = fitted(mod), name="fitted", mode = "lines") %>%
  layout(title = 'Height Vs. Weight Scatter Plot', plot_bgcolor = "#e5ecf6")

fig2

Image of code and plot

您的 lm 对象不符合分组模型(我猜是 continent

如果您的目的是绘制点和回归线,

您可以尝试使用 ggplot2

由于您没有提供数据,我以iris为例。

library(dplyr)
library(ggplot2)

iris %>%
  ggplot(aes(Sepal.Width, Sepal.Length, group = Species, color = Species)) +
  geom_smooth(method = "lm") +
  geom_point()