我想向使用分组数据(因子 x 轴)和对数刻度 y 轴创建的绘图添加背景填充。添加对数刻度后,背景填充将被删除。
这是一个错误,还是我做错了什么?
可重现的示例数据:我将使用mtcars
数据,但随着cyl
变量作为因子。这是模仿我的数据的最简单的数据集。
library(dplyr)
library(ggplot2)
mtcars_f <- mtcars %>%
mutate(cyl.f = factor(cyl))
这对于正常的 y 轴刻度来说效果很好。
mtcars_f %>%
ggplot(aes(cyl.f, mpg)) +
geom_rect(xmin=-Inf, ymin=17.5, xmax=Inf, ymax=22.5) +
geom_point()
问题:但是,当 y 轴变换时,背景矩形填充会被删除:
mtcars_f %>%
ggplot(aes(cyl.f, mpg)) +
geom_rect(xmin=-Inf, ymin=17.5, xmax=Inf, ymax=22.5) +
geom_point() +
scale_y_log10()
注意:这是一个不同的问题这个类似标题的问题 https://stackoverflow.com/questions/35197640/geom-rect-not-working-with-scale-y-log10-ggplot2
编辑答案:@Tung 的答案有效!这也可以通过将数据传递给来解决geom_rect
为了美观,您将 x 轴指定为“离散”
rect_df <-
data_frame(xmin=-Inf, ymin=17.5, xmax=Inf, ymax=22.5)
mtcars_f %>%
ggplot(aes(cyl.f, mpg)) +
geom_rect(data = rect_df, aes(xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax), inherit.aes = F) +
geom_point() +
scale_y_log10() +
scale_x_discrete()