Search code examples
rshinyggvis

ggvis layer_model_predictions polynomial fit


mtcars %>%
  ggvis(x = ~mpg, y = ~hp) %>%
  layer_points() %>%
  layer_model_predictions(model = "lm") 

gives a linear best fit line through the data. I am looking into how to make a best fit curve of order 2, 3, 4, etc. Based on the documentation for layer_model_predictions, it states that model "Must be the name of a function that produces a standard model object with a predict method." This leads to predict.poly. I know that means that I most likely need layer_model_predictions(model = "poly"), but how do you specify the order (degree) of the fit within the layer_model_predictions function call?

EDIT:

When the solution from eipi10 is applied to a reactive shiny app the accepted answer is giving some trouble. Posted as a new question here.


Solution

  • You can supply a formula to layer_model_predictions. For example, a third-order polynomial fit is given below.

    mtcars %>%
      ggvis(x = ~mpg, y = ~hp) %>%
      layer_points() %>%
      layer_model_predictions(model="lm", formula=hp ~ poly(mpg,3)) 
    

    This is slightly different from the way it works in ggplot2 with geom_smooth, where you always supply a formula in y and x (e.g., formula = y ~ poly(x,3)), regardless of the specific column names used for the y and x aesthetics.