tidyverse / ggplot2

An implementation of the Grammar of Graphics in R
https://ggplot2.tidyverse.org
Other
6.48k stars 2.02k forks source link

Axis breaks above max data value #6120

Open Olivia-Box-Power opened 2 hours ago

Olivia-Box-Power commented 2 hours ago

Often when producing a chart I'd like the top y axis break to be above the maximum data value. E.g. on the following chart I'd like there to be a break at 100.

library(ggplot2)

df <- data.frame(class = c("A", "B", "c"), value = c(80, 50, 95))

ggplot(df, aes(class, value)) +
  geom_col()

Created on 2024-09-25 with reprex v2.1.1

I can set the breaks manually using scale_y_continuous if I know what the data values are. However, often I don't know the range of values in advance.

This stack overflow post provides a solution to this problem, using the pretty function to set the breaks and limits in scale_y_continuous. I was wondering though if it would be possible to have an option in scale_x/y_continuous to say that the max axis break should be above the max value?

Apologies if this has been requested previously.

teunbrand commented 2 hours ago

I endorse Stefan's answer to this problem: use a function to set whatever rule you'd like for your limits. The function recieves the natural limits of the data and should return the limits you want to use.

Providing a function gives all sorts of flexibilities so that many rules about limits, breaks or labels don't need separate arguments in the scale functions.