如何将 Stat_smooth 或 geom_smooth 的输出存储为数据文件?

How to store the output of the Stat_smooth or geom_smooth as a data file?

我正在开发一个闪亮的应用程序,我在其中通过上传数据集生成各种散点图。我也在生成的散点图上使用 stat_smooth。现在,我希望能够将生成的 stat_smooth 配置文件存储为数据集。我该怎么做?

此外,我想在一张图中编译各种 stat_smooth 配置文件,这就是为什么我想将它们存储为数据集。

您可以使用 ggplot_build。这是一个例子:

library(ggplot2)

p <- ggplot(data = mtcars) +
  geom_point(aes(hp, mpg)) +
  stat_smooth(aes(hp, mpg))

p2 <- ggplot_build(p)

head(p2$data[[2]])

输出

    x        y     ymin     ymax       se PANEL group  colour   fill
1 52.00000 31.15895 27.03176 35.28614 2.009302     1    -1 #3366FF grey60
2 55.58228 30.51224 26.91154 34.11295 1.752985     1    -1 #3366FF grey60
3 59.16456 29.87138 26.72390 33.01886 1.532336     1    -1 #3366FF grey60
4 62.74684 29.23738 26.46507 32.00968 1.349680     1    -1 #3366FF grey60
5 66.32911 28.61085 26.13527 31.08643 1.205223     1    -1 #3366FF grey60
6 69.91139 27.99200 25.73825 30.24575 1.097226     1    -1 #3366FF grey60
  size linetype weight alpha
1    1        1      1   0.4
2    1        1      1   0.4
3    1        1      1   0.4
4    1        1      1   0.4
5    1        1      1   0.4
6    1        1      1   0.4