Search code examples
rggplot2plotlyggplotly

can stat_poly_eq() be added to plotly plot?


One can easily include stat_poly_eq() in ggplot, but is there any way to include this on a plotly plot?

When I tried using ggplotly, it does not render stat_poly_eq().

Or should I use a different function in the case of plotly?


Solution

  • You can change a ggplot including stat_poly_eq with ggplotly. The new plotly object still got the polynomial regression.

    Working example:

    library(ggplot2)
    library(ggpmisc)
    library(plotly)
    set.seed(4321)
    x <- 1:100
    y <- (x + x^2 + x^3) + rnorm(length(x), mean = 0, sd = mean(x^3) / 4)
    my.data <- data.frame(x = x, y = y,
                          group = c("A", "B"),
                          y2 = y * c(0.5,2),
                          w = sqrt(x))
    
    # give a name to a formula
    formula <- y ~ poly(x, 3, raw = TRUE)
    
    # no weights
    p<-ggplot(my.data, aes(x, y)) +
       geom_point() +
       geom_smooth(method = "lm", formula = formula) +
       stat_poly_eq(formula = formula, parse = TRUE)
    
    ggplotly(p)
    

    Plot

    Only difference is, that you don't get your textbox of R^2. There is nothing we can do about it, since it's not implemented yet (11.2020) as the error message shows.


    If this still does not work for you. You can just include a regression by hand and add it to plotly. This is taken from an existing solution. Check here for giving credits. This way it's easier to modify and you can add all the information you need.

      library(plotly)
      library(dplyr)
      data(cars, package = "datasets")
    
     qfit1 <- lm(dist ~ poly(speed,2), data = cars)
    
      cars %>%     
      plot_ly() %>%  
      add_lines(x = ~speed, y = fitted(qfit1)) %>%
      add_trace(x=~speed, y=~dist)
    

    Adding a text for your R squared could be:

      add_annotations(text= sprintf("R^2: %f", summary(qfit1)[8]), showarrow=FALSE, xref="paper", yref="paper", x=0.05,y=0.9)
    

    For more options and customization check the documentation off add_annotaions.

    [plot2]