【问题标题】:plotly regression line R情节回归线R
【发布时间】:2021-04-01 07:58:45
【问题描述】:

将回归线添加到“情节”散点图中的问题。 我已经完成了以下代码:

require(plotly)
data(airquality) 

## Scatter plot ##

c <- plot_ly(data = airquality, 
    x = Wind,
    y = Ozone, 
    type = "scatter",
    mode = "markers"
    )
c

## Adding regression line (HERE IS THE PROBLEM) ##

g <- add_trace(c, 
     x = Wind,
     y = fitted(lm(Ozone ~ Wind, airquality)),
     mode = "lines"
     )
g 

【问题讨论】:

  • 问得好,但我想你忘记了 "Wind" 之前的 "~" --> "x = ~Wind"。 " y = ~Ozone" 也一样

标签: r line regression linear-regression plotly


【解决方案1】:

我认为是缺失值引起的

airq <- airquality %>% 
  filter(!is.na(Ozone))

fit <- lm(Ozone ~ Wind, data = airq)

airq %>% 
  plot_ly(x = ~Wind) %>% 
  add_markers(y = ~Ozone) %>% 
  add_lines(x = ~Wind, y = fitted(fit))

【讨论】:

    【解决方案2】:

    使用layout去掉图例,trace添加回归线

    data("airquality")
    fv <- airquality %>% filter(!is.na(Ozone)) %>% lm(Ozone ~ Wind,.) %>% fitted.values()
    
    airquality %>% filter(!is.na(Ozone)) %>%
      plot_ly(x = ~Wind, y = ~Ozone, mode = "markers") %>% 
      add_markers(y = ~Ozone) %>% 
      add_trace(x = ~Wind, y = fv, mode = "lines") %>%
      layout(showlegend = F)
    

    【讨论】:

      猜你喜欢
      • 2013-02-11
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      相关资源
      最近更新 更多