ggvis layer_model_predictions 多项式拟合

ggvis layer_model_predictions polynomial fit

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

给出一条穿过数据的线性最佳拟合线。我正在研究如何根据 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 制作 2、3、4 等阶的最佳拟合曲线。我知道这意味着我很可能需要 layer_model_predictions(model = "poly"),但是如何在 layer_model_predictions 函数调用中指定拟合的顺序(程度)?

编辑:

当 eipi10 的解决方案应用于反应式闪亮应用程序时,接受的答案会带来一些麻烦。作为新问题发布

您可以提供 formulalayer_model_predictions。例如,下面给出了一个三阶多项式拟合。

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

这与它在带有 geom_smooth 的 ggplot2 中的工作方式略有不同,您总是在 yx 中提供公式(例如,formula = y ~ poly(x,3)) ,无论用于 yx 美学的特定列名称如何。