gosia
gosia

Reputation: 131

How to add R^2 using plotly in R?

I wonder how I can add regression line equation and R^2 value on the plot using plotly.

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

Upvotes: 2

Views: 3495

Answers (1)

MLavoie
MLavoie

Reputation: 9836

What about this?

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

Upvotes: 3

Related Questions