user2987808
user2987808

Reputation: 1437

Overriding panel.grid in ggplot2

The following code first drops the X-axis text, and then adds it back in with a red color:

p_text <- qplot(data = mtcars, x = hp, y = disp) + 
  theme(axis.text.x = element_blank())
p_text + theme(axis.text.x = element_text(colour = "red"))

Similarly, one would expect this code to do the same thing for the grid lines:

p_grid <- qplot(data = mtcars, x = hp, y = disp) + 
  theme(panel.grid = element_blank())
p_grid + theme(panel.grid = element_line(colour = "red"))

However, it only appears to add them back with default colors. Why this strange behavior, and is there a way to add the panel grid lines back in? (My actual example involves overriding various pre-set themes, so just setting the grid lines right away is not an option).

Upvotes: 1

Views: 527

Answers (1)

Roland
Roland

Reputation: 132676

If you look at theme_grey you can see that panel.grid.minor and panel.grid.major are both specified. When you specify panel.grid to a specific color, the minor and major grid lines would inherit this if a color wasn't specified for them. But there is.

This works as expected:

p_grid <- qplot(data = mtcars, x = hp, y = disp) + 
  theme(panel.grid = element_blank())
p_grid + theme(panel.grid = element_line(colour = "blue"), #needed to overwrite element_blank
               panel.grid.major = element_line(colour = "red"),
               panel.grid.minor = element_line(colour = "red"))

and this too:

p_grid + theme(panel.grid = element_line(colour = "red"), 
               panel.grid.major = NULL,
               panel.grid.minor = NULL)

Upvotes: 2

Related Questions