user2363777
user2363777

Reputation: 1071

Ggplot minor gridlines not showing when they coincide with (disabled) major gridlines

I created a graph plotting data by day of the year with an x-axis where the tick marks indicate the start of each month and the minor grid lines indicate the start of each week.

I intentionally don't show the major grid lines on the x-axis, which would make the graph too busy. However, this has an unexpected effect: the minor grid lines don't show when they coincide with a (disabled) major grid line. (That is, whenever the first day of the month falls on a Monday, here, Jan 1st and Oct 1st 2018.)

Could this be a bug, and is there a way to work around this issue?

library(tidyverse)
library(lubridate)

dat = tibble(
  date = as_date(c("2018-01-01", "2019-01-01")),
  proportion = c(.2, .8)
)

dat %>% 
  ggplot(aes(x = date, y = proportion)) +
  geom_point() +
  scale_x_date(breaks = "1 month", minor_breaks = "1 week", date_labels = "%b") +
  scale_y_continuous(limits = c(0, 1)) +
  theme(
    panel.grid.major.x = element_blank(),
    panel.grid.minor.y = element_blank()
  )

graph

Upvotes: 4

Views: 1760

Answers (1)

Z.Lin
Z.Lin

Reputation: 29085

Actually, this is intended behaviour. See discussion under this (really old) issue on GitHub, which resulted in ggplot2:::guide_grid (an un-exported function that manipulates the gridlines before a ggplot object is printed) keeping only minor gridlines that don't overlap with major ones:

> ggplot2:::guide_grid
function (theme, x.minor, x.major, y.minor, y.major) {
  x.minor <- setdiff(x.minor, x.major)
  y.minor <- setdiff(y.minor, y.major)
  ...
}

Workaround

One quick & dirty way to get around this is to run trace(ggplot2:::guide_grid, edit=TRUE) beforehand, & manually remove the x.minor <- setdiff(x.minor, x.major) line from code in the popup window.

Your code should work as expected thereafter:

plot

(This effect will end when you close your R session, or earlier if you run untrace(ggplot2:::guide_grid)).

Upvotes: 2

Related Questions