如何在R中使用plotly添加R ^ 2?

时间:2016-02-03 13:57:10

标签: r plotly r-plotly

我想知道如何使用 plotly 在图上添加回归线方程和R ^ 2值。

library(plotly)

x=c(1518,1655,3000,1720,1998,3455,2329,2868,2674,3207,3044,3301,3606,4700,3724,5111,3684,5586,4534,3313,3000,4340,5269, 6568)
y=c(1609,1776,2999,1908,2024,3489,2424,2931,2779,3224,3098,3356,3571,4861,3632,5522,3722,5698,4361,3399,3000,4086,5063,6246)
reg = lm(y ~ x)
modsum = summary(reg)
R2 = summary(reg)$r.squared

# plot
plot_ly(x = x, y = y, type = "scatter", mode = "markers", themes="Catherine")
add_trace(y = reg$fitted.values, type = "scatter", mode = "lines", name = "reg", line = list(width = 2))

1 个答案:

答案 0 :(得分:3)

这个怎么样?

plot_ly(x = x, y = y, type = "scatter", mode = "markers", themes="Catherine")
add_trace(y = reg$fitted.values, type = "scatter", mode = "lines", name = "reg", line = list(width = 2)) %>%
  layout(
    showlegend = F,
    annotations = list(x = x, y = y, text = "R2=0.9870744", showarrow = T)
  )

enter image description here