【发布时间】:2021-02-11 04:22:51
【问题描述】:
假设一个数据集包含多个时间段和多个组的计数数据,格式如下:
set.seed(123)
df <- data.frame(group = as.factor(rep(1:3, each = 50)),
week = rep(1:50, 3),
rate = c(round(700 - rnorm(50, 100, 10) - 1:50 * 2, 0),
round(1000 - rnorm(50, 200, 10) - 1:50 * 2, 0),
round(1000 - rnorm(50, 200, 10) - 1:50 * 2, 0)))
group week rate
1 1 1 604
2 1 2 598
3 1 3 578
4 1 4 591
5 1 5 589
6 1 6 571
7 1 7 581
8 1 8 597
9 1 9 589
10 1 10 584
我有兴趣为每组拟合基于模型的趋势线,但是,我希望仅从某个 x 值显示此趋势线。使用所有数据点可视化趋势线(需要ggplot2):
df %>%
ggplot(aes(x = week,
y = rate,
group = group,
lty = group)) +
geom_line() +
geom_point() +
geom_smooth(method = "glm",
method.args = list(family = "quasipoisson"),
se = FALSE)
或者根据特定范围的值拟合模型(需要ggplot2 和dplyr):
df %>%
group_by(group) %>%
mutate(rate2 = ifelse(week < 35, NA, rate)) %>%
ggplot(aes(x = week,
y = rate,
group = group,
lty = group)) +
geom_line() +
geom_point() +
geom_smooth(aes(y = rate2),
method = "glm",
method.args = list(family = "quasipoisson"),
se = FALSE)
但是,我找不到使用所有数据拟合模型的方法,而是仅显示特定 x 值(比如 35+)的趋势线。因此,我本质上想要为图一计算的趋势线,但根据第二个图显示它,使用ggplot2,理想情况下只有一条管道。
【问题讨论】:
-
通过
xseq:geom_smooth(method = "glm", method.args = list(family = "quasipoisson"), xseq=seq(35,50,by=1), se = FALSE) -
@user20650 这与我正在寻找的非常接近。唯一需要注意的是,它需要指定上限。我只想指定下限。