The panel grid of ggplot2 plots is created to be on the background of the plot. My question is: is it possibly modified to be brought over the plot?
I can partly see the solution in substituting the grid by geom_hline()
or geom_vline()
layers. However, that can be tricky with more complicated plots or while plotting maps, and thus my question is only concerning modifying the elements of theme()
.
library(tidyverse)
df <- data.frame(x = c(1,2),
y = c(1,2))
df %>% ggplot(aes(x, y)) +
geom_area() + theme(
panel.grid = element_line(color = "red")
)
A cheaty solution of substituting the grid by geom_hline()
or geom_vline()
grd_x <- seq(1, 2, length.out = 9)
grd_y <- seq(0, 2, length.out = 9)
df %>% ggplot(aes(x, y)) +
geom_area() +
geom_hline(yintercept = grd_y, col = "red") +
geom_vline(xintercept = grd_x, col = "red")
As mentioned in 1 of the comments, you can use theme(panel.ontop = TRUE)
. However, when trying this, I couldn't see the graph anymore. Therefore you need to make sure the background image of the panel is blank when doing changing panel.ontop
to TRUE
:
library(tidyverse)
df <- data.frame(x = c(1,2),
y = c(1,2))
df %>% ggplot(aes(x, y)) +
geom_area() +
theme(panel.grid = element_line(color = "red"),
panel.ontop = TRUE, panel.background = element_rect(color = NA, fill = NA)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With