Search code examples
ggplot2scalefacetaxis-labelsyaxis

How to set the number of y-axis values displayed when faceting


I have a faceted bar graph.

 dat <- data.frame(ID = c("A", "A", "B", "B", "C", "C"),
                   A = c("Type 1", "Type 2", "Type 1", "Type 2", "Type 1", "Type 2"),
                   B = c(1, 2, 53, 87, 200, 250))

 ggplot(data = dat, aes(x = A, y = B)) + 
   geom_bar(stat = "identity") +
   facet_wrap(~ID, scales= "free_y")

How do I code to only have 3 y-axis values displayed per graph?

I've tried

   +scale_y_continuous(breaks=3)

Solution

  • To get more control over the breaks you can write your own breaks function. The following code gives you exactly 3 breaks. However, this very basic approach does not necessarily result in "pretty" breaks:

    library(ggplot2)
    
    my_breaks <- function(x) { 
      seq(0, round(max(x), 0), length.out = 3) 
    } 
    
    my_limits <- function(x) { 
      c(x[1], ceiling(x[2]))
    }
    
    # Dataset 2
    dat <- data.frame(
      ID = c("A", "A", "A","B", "B", "B", "C", "C", "C"), 
      A = c("Type 1", "Type 2", "Type 3", "Type 1", "Type 2", "Type 3","Type 1", "Type 2", "Type 3"), 
      B = c(1.7388, 4.2059, .7751, .9489, 2.23405, .666589, 0.024459, 1.76190, 0.066678)) 
    
    ggplot(data = dat, aes(x = A, y = B)) + 
      geom_bar(stat = "identity") + 
      facet_wrap(~ID, scales= "free_y") + 
      scale_y_continuous(breaks = my_breaks, limits = my_limits)
    

    # Dataset 1
    dat <- data.frame(ID = c("A", "A", "B", "B", "C", "C"),
                      A = c("Type 1", "Type 2", "Type 1", "Type 2", "Type 1", "Type 2"),
                      B = c(1, 2, 53, 87, 200, 250))
    
    ggplot(data = dat, aes(x = A, y = B)) + 
      geom_bar(stat = "identity") + 
      facet_wrap(~ID, scales= "free_y") + 
      scale_y_continuous(breaks = my_breaks, limits = my_limits)
    

    Created on 2020-04-10 by the reprex package (v0.3.0)