Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

r - 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.

question from:https://stackoverflow.com/questions/65908472/how-do-i-adjust-visibility-of-gridlines-in-ggplot-chart

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 you could adjust it via the hex color code:

  1. I make use of the default grid line color "grey92" which has rgb values (235, 235, 235).

  2. To set the opacity I use rgb() which as a fourth argument takes the opacity or alpha which I reduce to a value of 100:

library(ggplot2)
library(dplyr)

data = mtcars

# Reduce the opacity of the grid lines: Default is 255
col_grid <- rgb(235, 235, 235, 100, maxColorValue = 255)

data %>% 
  select(mpg, disp) %>% 
  ggplot(aes(disp, mpg))+
  geom_point(size = 3)+
  theme_bw() +
  theme(panel.grid = element_line(color = col_grid))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...