Search code examples
rggplot2

How do I adjust visibility of gridlines in ggplot chart


The code below creates a scatter plot and uses theme_bw with has gridlines in the background -

data = mtcars

data %>% 
  select(mpg, disp) %>% 
  ggplot(aes(disp, mpg))+
  geom_point(size = 3)+
  theme_bw()

I would like to also include some vertical and horizontal lines on the chart. However with the current gridlines, it looks a bit busy. Is there a way to further reduce the visibility of the gridlines. I don't want want remove them completely.


Solution

  • This could be achieved by switching to a lighter color or by reducing the opacity of the color used for the grid lines which both could be achieved via theme option panel.grid. Below I show the second approach. Unfortunately element_line has no alpha argument to set the opacity but we can use scales::alpha() to this end:

    library(ggplot2)
    library(dplyr, warn = FALSE)
    
    data <- mtcars
    
    col_grid <- scales::alpha("grey92", .6)
    
    data %>%
      select(mpg, disp) %>%
      ggplot(aes(disp, mpg)) +
      geom_point(size = 3) +
      theme_bw() +
      theme(panel.grid = element_line(color = col_grid))