ggplot2 icon indicating copy to clipboard operation
ggplot2 copied to clipboard

Discrete scales don't use `names(breaks)` for default-labels

Open teunbrand opened this issue 1 year ago • 0 comments

As the title implies, continuous scales use names(breaks) as their labels, whereas discrete scales do not:

library(ggplot2)

ggplot(mpg, aes(drv, hwy)) +
  geom_boxplot() +
  scale_y_continuous(
    breaks = c(twenty = 20, thirty = 30, fourty = 40)
  ) +
  scale_x_discrete(
    breaks = c("four-wheel" = 4, forward = "f", reverse = "r")
  )

Created on 2024-10-18 with reprex v2.1.1

I think we should probably mirror this mechanism in discrete scales, so that the x-axis above has the labels 'four-wheel', 'forward' and 'reverse'.

The reason continuous scales have this mechanism is because labels = waiver() (the default) let's the transformation's format method label the breaks. Many such formatters return names first and only format when names are absent.

scales::transform_identity()$format
#> function (x) 
#> {
#>     if (!is.null(names(x))) {
#>         return(names(x))
#>     }
#>     ret <- format(x, ..., trim = TRUE, justify = "left")
#>     ret[is.na(x)] <- NA
#>     ret
#> }
#> <bytecode: 0x000002080e0c05d8>
#> <environment: 0x000002080e09fc70>

Created on 2024-10-18 with reprex v2.1.1

teunbrand avatar Oct 18 '24 13:10 teunbrand