elliot
elliot

Reputation: 1944

Change a single gridline color in ggplot2?

Is it possible to control the color of specific lines in the panel grid in ggplots? I'd like to have a "decorative" line indicate the 0 on the y-axis, using geom_hline. You can see from the code and plot below, that just adding geom_hline keeps the grey gridlines. I'd like for the line crossing the y-axis to be transparent and the rest of the gridlines to remain grey.

library(ggplot2)
ggplot(data = NULL)+
  geom_hline(yintercept = 0, linetype = 4, size = 2)+
  theme_minimal()+
  theme(panel.grid = element_line(size = 2))

enter image description here

Upvotes: 1

Views: 1945

Answers (1)

camille
camille

Reputation: 16842

Because ggplot layers are drawn in the order they're received, you can draw a geom_hline below the dashed one (same size as the gridlines or bigger), make it the same color as the background fill, and it will block out the gridline.

In an easy case, you know the background color (in this case, it's white):

library(ggplot2)
ggplot(data = NULL) +
  geom_hline(yintercept = 0, size = 2, color = "white") +
  geom_hline(yintercept = 0, linetype = 4, size = 2) +
  theme_minimal() +
  theme(panel.grid = element_line(size = 2))

To make it more dynamic and match with themes, take the fill of the theme's plot background, and set that as the color:

ggplot(data = NULL) +
  geom_hline(yintercept = 0, size = 2, 
             color = theme_dark()$panel.background$fill) +
  geom_hline(yintercept = 0, linetype = 4, size = 2) +
  theme_dark() +
  theme(panel.grid = element_line(size = 2))

Upvotes: 3

Related Questions