Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bring to front the panel grid

Tags:

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")
  )

The red coloured grid is to be brought to the front:

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")

The expected output.

like image 710
Kryštof Chytrý Avatar asked Jul 13 '19 11:07

Kryštof Chytrý


1 Answers

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)
  )

enter image description here

like image 104
Sven Avatar answered Sep 30 '22 19:09

Sven