简体   繁体   English

绘图回归线 R

[英]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

在此处输入图片说明

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

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

在此处输入图片说明

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

在此处输入图片说明

Use layout to remove the legend, and trace to add regression line使用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)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM