Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plotly regression line R

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

like image 535
Monteiro Avatar asked Jul 26 '16 14:07

Monteiro


2 Answers

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

like image 169
JohnCoene Avatar answered Sep 20 '22 14:09

JohnCoene


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

like image 38
Rafael Díaz Avatar answered Sep 20 '22 14:09

Rafael Díaz