Search code examples
rtidyverse

How to add minor gridlines inside scale_x_discrete


I am getting an error message when trying to add minor gridlines while using scale_x_discrete. How can I do this?

library(tidyverse);library(scales)

data:
w_dat <- structure(list(IDWeek = c(1, 32, 33, 34, 35, 36, 37, 38, 39, 
42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52), race = c("W", "W", 
"W", "W", "W", "W", "W", "W", "W", "W", "W", "W", "W", "W", "W", 
"W", "W", "W", "W", "W"), FishPassage = c(3102, 8, 115, 197, 
334, 1184, 67350, 80494, 351200, 1113, 217242, 1927, 219973, 
104983, 85756, 66239, 75423, 140612, 33838, 10152)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -20L))

#WORKS without minor gridlines
ggplot(winter_dat,aes(x=factor(IDWeek),y=FishPassage, fill=race)) + geom_bar(stat='identity', show.legend=FALSE) + theme_bw(base_size = 9) +  xlab("Week") +
facet_grid(race~. , scales = "free_y") + scale_fill_brewer(palette = "Set1") + scale_y_continuous(labels=comma) +
scale_x_discrete(limits = factor(1:52), breaks = seq(1,52,3))

#Trying to add minor gridlines throws an error
ggplot(winter_dat,aes(x=factor(IDWeek),y=FishPassage, fill=race)) + geom_bar(stat='identity', show.legend=FALSE) + theme_bw(base_size = 9) +  xlab("Week") +
facet_grid(race~. , scales = "free_y") + scale_fill_brewer(palette = "Set1") + scale_y_continuous(labels=comma) +
scale_x_discrete(limits = factor(1:52), breaks = seq(1,52,3), minor_breaks = seq(1,52, 1))

I get this error:
Error in discrete_scale(c("x", "xmin", "xmax", "xend"), "position_d",  : 
  unused argument (minor_breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52))
 
  

Solution

  • Unlike scale_x_continuous, the scale_x_discrete function doesn't accept a minor_breaks argument.

    ggplot(winter_dat,aes(x=IDWeek, y=FishPassage, fill=race)) + 
      geom_bar(stat='identity', show.legend=FALSE) + 
      theme_bw(base_size = 9) +  
      xlab("Week") +
      facet_grid(race~. , scales = "free_y") + 
      scale_fill_brewer(palette = "Set1") + 
      scale_y_continuous(labels=scales::comma) +
      scale_x_continuous(limits=c(1,52), 
                         breaks = seq(1,52,3), 
                         minor_breaks = seq(1,52, 1)) 
    

    enter image description here