A brief description of how all scale_* functions work in ggplot2

The Issue

This is an issue I faced whilst working as a developer on the dabestr rebuild sometime back. You might have also encountered this before - its the issue of “floating bar graphs” such as the one below.

library(ggplot2)

g <- ggplot(mpg, aes(class)) +
  geom_bar()
g

The Fix

g <- ggplot(mpg, aes(class)) +
  geom_bar() +
  coord_cartesian(ylim = c(0, 60),  
                  expand = FALSE)   
g
  1. Note that we used coord_cartersian here instead of scale_y_continuous. More details can be found on ggplot’s official documentation regarding this topic. To summarise what the documentation states, coord_cartesian can essentially be seen as zooming in closer to the plot whilst scale_* functions shrinks the limits directly, thereby eliminating possible lines or dots from being drawn.