rggplot2gridlines

Is there a way I can add log gridlines to my graph with RStudio?


I'm currently trying to create a dose-response curve with Rstudio and I'm using the tidydrc package. I was wondering if there was a way I could add minor gridlines, since the x-axis is log.

Here's an image of what I've got so far

enter image description here

This is the code I've got so far:

tidydrc_plot(Nifedipinedrc,ed50=FALSE)  + 
  scale_x_log10() + 
  geom_errorbar(aes(ymin=g$Nifedipine-g$SD, ymax=g$Nifedipine+g$SD, x=Nifedipinedrc[[1]][[1]]$d, y=Nifedipinedrc[[1]][[1]]$r)) +
  ggtitle("graph") +
  labs(x="Concentration", y= "Force")

I know it's an absolute mess of a code but I'm completely self taught and I feel like I've hit a bit of a brick wall with this because I don't actually understand a lot of the guides currently on stack.


Solution

  • Here is a function that you can use for the minor_breaks argument of log scales. The proposed function uses an unexported function from ggplot2, so I'm cheating a little bit. This probably only works well for log10 axis though and you might want to accentuate the major gridlines some more through the theme() setting.

    library(ggplot2)
    
    # A function factory for minor log breaks
    minor_breaks_log <- function(base) {
      # Prevents lazy evaluation
      force(base) 
      # Wrap calculation in a function that the outer function returns
      function(limits) {
        ggplot2:::calc_logticks(
          base = base, 
          minpow = floor(log(limits[1], base = base)), 
          maxpow = ceiling(log(limits[2], base = base))
        )$value
      }
    }
    
    ggplot(msleep, aes(bodywt, brainwt)) +
      geom_point() +
      scale_y_log10(minor_breaks = minor_breaks_log(10)) +
      scale_x_log10(minor_breaks = minor_breaks_log(10))
    #> Warning: Removed 27 rows containing missing values (geom_point).
    

    Created on 2020-12-02 by the reprex package (v0.3.0)