我在构面中绘制不同的时间序列,并且我想使用 annotate() 为其中一个构面创建不同的背景颜色。一个方面代表 2018 年的最后 15 周(第 38 - 52 周),而另一个方面代表 2019 年的前 15 周(第 1 - 15 周)。我想在 2019 年仅更改第 5-8 周的背景颜色。但是,当我尝试这样做时,R 会将 2018 年的 x 轴范围从第 38-52 周更改为第 1-52 周。
我试图在 2019 年的图中仅创建一个第 5-8 周的矩形,如下所示:
annotate("rect", xmin = 5, xmax = 8, min = 0, ymax = Inf, alpha = 0.3, fill="grey") +
我正在使用的代码是:
library(ggthemes)
week <- c(38:52, 1:15)
minutes <- sample(160, 30, replace=T)
year <- c(rep(2018, 15), rep(2019,15))
dat <- data.frame(year, week, minutes)
ggplot(dat, aes(week, minutes, group=year)) +
annotate("rect", xmin = 5, xmax = 8, min = 0, ymax = Inf, alpha = 0.3, fill="grey") +
geom_line(size=1, color="black") +
geom_point(size=2, color="black") +
theme_fivethirtyeight() +
facet_wrap(~ year, scales = "free") +
scale_y_continuous(limits=c(0,200))
我希望有两个方面:一个是 2018 年的结果,x 轴范围在 38-52 之间,另一个是 2019 年的结果,x 轴范围在 1-15 之间。
实际结果是 2018 年的结果,x 轴范围在 1-52 之间,而 2019 年的结果,x 轴范围在 1-15 之间。
最佳答案
Annotate
不能这样做,因为你不能用你的刻面变量( year
)提供它,但是你可以使用 geom_rect
来做到这一点.为此,您必须传递一个包含分面变量 ( year
) 的数据帧:
感谢@aosmith ,现在 geom_rect 只绘制一次:
ggplot(dat, aes(week, minutes, group=year)) +
geom_line(size=1, color="black") +
geom_point(size=2, color="black") +
facet_wrap(~ year, scales = "free") +
theme_fivethirtyeight() +
scale_y_continuous(limits=c(0,200)) +
geom_rect(data = data.frame(year = 2019), aes(xmin = 5, xmax = 8, ymin = 0, ymax = Inf), alpha = 0.3, fill="grey", inherit.aes = FALSE)
这将产生所需的情节:
关于r - 在 x 轴上绘制时间序列时,对 ggplot 中的一个方面使用 annotate ("rect"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55748379/