Search code examples
rggplot2axessubtitle

How to add subtext to axes in ggplot2 R


For the main y-axis and x-axis, I have generic titles like "Tank's Ratio" and "Counts". I want a second line of label where I specify the ratio and counts. eg. Just below "Tank's Ratio" I want "# in water/# in sand" in a smaller font but along the y-axis. Similarly for the x-axis. Here is the basic code

data <- data.frame(set = c(1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 4, 4), density = c(1, 3, 3, 1, 3, 1, 1, 1, 3, 3, 1, 3), counts = c(100, 2, 3, 76, 33, 12, 44, 13, 54, 36, 65, 1), ratio = c(1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 90, 1))

library(ggplot2)

ggplot(data, aes(x = counts, y = ratio)) + 
  geom_point() + 
  ylab("Tank's Ratio") + 
  xlab("Counts") 

Solution

  • It's not the most elegant solution, but hope it helps:

    library(ggplot2)
    library(gridExtra)
    library(grid)
    

    First, create plot without ylab:

    g <- ggplot(data, aes(x = counts, y = ratio)) + 
      geom_point()  +
      ylab("") + 
      xlab("Counts") 
    

    Then add subtitle for both axis:

    g2 <- grid.arrange(g, 
                       bottom = textGrob("in water/ # in sand", 
                                         x = 0.55, y = 1, gp = gpar(fontsize = 9)),
                       left = textGrob("in water/ # in sand",  rot = 90, 
                                       x = 1.5, gp = gpar(fontsize = 9)))
    

    And finally, add description of y-axis

    grid.arrange(g2, 
                 left = textGrob("Tank's Ratio",  rot = 90, 
                                 x = 1.7, gp = gpar(fontsize = 12)))
    

    enter image description here