plotly regression line R
Asked Answered
H

2

11

Problem with adding a regression line to a 'plotly' scatter plot. I've done the following code:

require(plotly)
data(airquality) 

## Scatter plot ##

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

enter image description here

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

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

enter image description here

Handbreadth answered 26/7, 2016 at 14:48 Comment(2)
See this threadStalinism
Good question but I think you forgot the "~" before "Wind" --> "x = ~Wind". Same for " y = ~Ozone"Squid
S
16

I reckon it's caused by the missing values

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))

enter image description here

Scissure answered 22/3, 2017 at 8:17 Comment(0)
C
5

Use layout to remove the legend, and trace to add regression line

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)

enter image description here

Convulse answered 12/9, 2018 at 6:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.