Search code examples
rggplot2boxplotyaxis

How to change the limits from scale_y_continuous depending on the plot in R?


I want to draw boxplots with the number of observations on top. The problem is that depending on the information and the outliers, the y-axis changes. For that reason, I want to change the limits of scale_y_continuous automatically. Is it possible to do this?

This is a reproducible example:

library(dplyr)
library(ggplot2)

myFreqs <- mtcars %>%  
  group_by(cyl, am) %>% 
  summarise(Freq = n()) 
myFreqs

p <- ggplot(mtcars, aes(factor(cyl), drat, fill=factor(am))) +
  stat_boxplot(geom = "errorbar") +
  geom_boxplot() +
  stat_summary(geom = 'text', label = paste("n = ", myFreqs$Freq), fun = max, position = position_dodge(width = 0.77), vjust=-1)

p

image 1

The idea is to increase at least +1 to the maximum value of the plot with the highest y-axis value (in the case explained above, it would be the second boxplot with n=8)

I have tried to change the y-axis with scale_y_continuous like this:

p <- p + scale_y_continuous(limits = c(0, 5.3))
p

image 2

However, I don't want to put the limits myself, I want to find a way to modify the limits according to the plots that I have. (Because... what if the information changes?). Is there a way to do something like this? With min and max --> scale_y_continuous(limits = c(min(x), max(x)))

Thanks very much in advance


Solution

  • Thanks to @teunbrand and @caldwellst I got the solution that I needed it.

    There are 3 solutions that work perfectly:

    1-

    p + scale_y_continuous(limits = function(x){
      c(min(x), (max(x)+0.1))
        })
    p
    

    2-

    library(tidyverse)
    
    p + scale_y_continuous(limits = ~ c(min(.x), max(.x) + 0.1))
    

    3-

    p + scale_y_continuous(limits = function(x){
      c(min(x), ceiling(max(x) * 1.1))
    })