2

我想知道如何使用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))
4

1 回答 1

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

在此处输入图像描述

于 2016-02-03T14:07:12.140 回答