gpt4 book ai didi

r - 如何扩展分位数回归线 geom_quantile 以在 ggplot 中进行预测?

转载 作者:行者123 更新时间:2023-12-05 04:34:42 25 4
gpt4 key购买 nike

我正在尝试绘制一组数据的分位数回归线。我想扩展 geom_quantile() 中的分位数回归线,以显示它们如何预测类似于使用 stat_smooth() 并将全范围参数设置为 TRUE。但是,geom_quantile() 没有全范围参数。示例如下:

data("mpg")
library(ggplot2)
library(dplyr)

m <-
ggplot(mpg, aes(displ,1/ hwy)) +
geom_point()
m + geom_quantile() +
scale_x_continuous(limits = c(1,9),
breaks = waiver(),
n.breaks = 8)

p <-
ggplot(mpg, aes(displ,1/ hwy)) +
geom_point()
p + stat_smooth(method = lm, fullrange = TRUE, se = FALSE, color = "red") +
scale_x_continuous(limits = c(1,9),
breaks = waiver(),
n.breaks = 8)

m1 <-
ggplot(mpg, aes(displ,1/ hwy)) +
geom_point()
m1 + geom_quantile(fullrange = TRUE) +
scale_x_continuous(limits = c(1,9),
breaks = waiver(),
n.breaks = 8)

m 的第一部分给出了数据集的分位数回归线。对于 p,我可以显示线性回归线预测到 9 的位移。但是对于 m1,我无法扩展回归线。有没有办法让我告诉 ggplot 做这种预测?当然,越简单越好,但我会考虑任何建议。提前致谢!

最佳答案

在引擎盖下,geom_quantile 使用 quantreg::rq,直接使用它可以非常简单地使用 geom_abline 产生相同的效果:

mod  <- quantreg::rq(I(1/hwy) ~ displ, tau = c(0.25, 0.5, 0.75), data = mpg)
r_df <- setNames(as.data.frame(t(coef(mod))), c("intercept", "gradient"))

m1 + geom_abline(data = r_df, aes(slope = gradient, intercept = intercept)) +
scale_x_continuous(limits = c(1,9),
breaks = waiver(),
n.breaks = 8)

enter image description here

关于r - 如何扩展分位数回归线 geom_quantile 以在 ggplot 中进行预测?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71164664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com