如何在两个向量之间建立线性关系?

时间:2018-02-03 17:00:16

标签: r plot plotly r-plotly

我正在尝试用plot_ly

制作相关图

作为一个例子,我做

library(plotly)

d <- diamonds[sample(nrow(diamonds), 1000), ]

p <- plot_ly(
  d, x = ~carat, y = ~price,
  # Hover text:
  text = ~paste("Price: ", price, '$<br>Cut:', cut),
  color = ~carat, size = ~carat
)

然后绘制

但是如何制作线性线并计算R2呢? 有办法吗?

如果您知道其他任何方式,请告诉我。

例如,像这样的东西会很棒

[![enter image description here][1]][1]

http://vault.hanover.edu/~altermattw/courses/220/R/corr/corr_2.html

我尝试用:

library(ggplot2)
ggplot(d, aes(x=carat, y=price)) +
        geom_point(aes(colour = Outcome)) +     
        geom_smooth(method=lm) 

我收到错误。

1 个答案:

答案 0 :(得分:3)

你可以试试这个:

fit <- lm(price ~ carat-1, data = d)
summary(fit)$adj.r.squared

a <- list(
    x = 2,
    y = 5000,
    text = "R2 = 0.88",
    xref = "x",
    yref = "y",
    showarrow = FALSE,
    arrowhead = 7
)


plot_ly() %>% add_markers(data = d, x= ~ carat, y = ~ price, color = ~carat, size = ~carat, name = "Size", marker=list(colorbar=list(title='Colorbar'))) %>%  
    add_lines(x = ~carat, y = fitted(fit), name = "Regression line") %>% 
    layout(annotations = a)

enter image description here