I want to add a background fill to a plot created with grouped data (factor x axis) and a log-scale y axis. When the log-scale is added, the background fill is removed.
Is this a bug, or am I doing something wrong?
Reproducible Example data:
I'll use the mtcars
data, but with the cyl
variable as a factor. This is the simplest dataset that mimics my data.
library(dplyr)
library(ggplot2)
mtcars_f <- mtcars %>%
mutate(cyl.f = factor(cyl))
This works fine with a normal y-axis scale.
mtcars_f %>%
ggplot(aes(cyl.f, mpg)) +
geom_rect(xmin=-Inf, ymin=17.5, xmax=Inf, ymax=22.5) +
geom_point()
The Problem: However, the background rectangle fill is removed when the y-axis is transformed:
mtcars_f %>%
ggplot(aes(cyl.f, mpg)) +
geom_rect(xmin=-Inf, ymin=17.5, xmax=Inf, ymax=22.5) +
geom_point() +
scale_y_log10()
note: this is a different issue than this similarly titled question
EDIT with answer: The answer by @Tung works! This can also be worked around by passing the data to geom_rect
as an aesthetic, and you specify the x-axis as "discrete"
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()