如何在使用plot_smooths()函数显示的GAM结果图中添加点?

问题描述 投票:0回答:1

我无法将点添加到使用 tidymv 包的plot_smooths()函数显示的GAM结果图表中。

我想向使用plot_smooths() 函数显示的GAM 结果图表添加点。 例如;

library(mgcv)
library(tidymv)
library(gratia)

x<-c(0.17,0.19,0.18,0.33,0.24,0.2,0.2,0.19,0.36,0.29,0.24,0.24,0.21,0.23,0.31,0.36,0.33,0.24,0.31)
y<-c(8475,86,209,8230,8372,8475,8475,2867,149,8410,8161,8474,8451,282,7409,682,504,66,315)
dat<-data.frame(x,y)
gam <- gam(y ~ s(x), data=dat)
plot_smooths(gam, x)

在此输入图像描述 我希望向此状态下显示的图表添加点。

我知道gratia包的plot.gam()和daw()函数在“residuals = TRUE”时显示点。

plot.gam(gam,residuals = TRUE)
draw(gam, residuals = TRUE)

在此输入图像描述 在此输入图片描述

但是,在这种情况下,y 轴值与实际数据值不同。 我想绘制所用数据的值。 请告诉我是否有办法绘制plot.gam() 函数或draw() 函数中使用的数据值。

提前谢谢您。

r mgcv gratia
1个回答
0
投票

您可以通过以下方式实现这一目标:

library(mgcv)
library(tidymv)
library(ggplot2)

x <- c(0.17, 0.19, 0.18, 0.33, 0.24, 0.2, 0.2, 0.19, 0.36, 0.29, 0.24, 0.24, 0.21, 0.23, 0.31, 0.36, 0.33, 0.24, 0.31)
y <- c(8475, 86, 209, 8230, 8372, 8475, 8475, 2867, 149, 8410, 8161, 8474, 8451, 282, 7409, 682, 504, 66, 315)
dat <- data.frame(x, y)

gam_model <- gam(y ~ s(x), data=dat)

smooth_plot <- plot_smooths(gam_model, "x")

smooth_plot +
  geom_point(data = dat, aes(x = x, y = y), color = "red", size = 2)

这给出了

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.