ggplot2 icon indicating copy to clipboard operation
ggplot2 copied to clipboard

Feature request: expose `palette` in discrete position scales

Open teunbrand opened this issue 3 months ago • 2 comments

The idea behind exposing a palette to discrete position scales is that the palette can be used to set custom spacings between discrete variables. Currently the 'palette' of discrete position scales is essentially seq_along(), and the ask here is to open this up to other functions that can translate discrete variables to continuous positions.

To give an example, let's say I have the following plot with a fake continuous scale separating groups of clarity:

library(ggplot2)

clarity_position <- function(x) {
  as.integer(x) + c(0, 1, 1, 2, 2, 3, 3, 4)[match(x, levels(x))] 
}
ggplot(diamonds, aes(clarity_position(clarity), price, group = clarity)) +
  geom_boxplot() +
  scale_x_continuous(
    breaks = c(1, 3, 4, 6, 7, 9, 10, 12),
    labels = levels(diamonds$clarity)
  )

Created on 2024-03-12 with reprex v2.1.0

I'd like to express a similar plot in the following way:

ggplot(diamonds, aes(clarity, price)) +
  geom_boxplot() +
  scale_x_discrete(
    palette = \(x) c(1, 3, 4, 6, 7, 9, 10, 12)
  )

I'd imagine it just uses the discrete expansion rules and not show minor breaks in the panel grid.

teunbrand avatar Mar 12 '24 11:03 teunbrand

This looks useful :)

Wondering whether this argument should be called pal instead of palette, so that it aligns with {scales} terminology?

Or maybe the logic is a function that creates a palette uses pal_* and an argument within a function is called palette?

davidhodge931 avatar Apr 04 '24 00:04 davidhodge931

I don't think it is worth the hassle renaming the palette argument for this particular request as palette is a pre-existing argument to the scale constructors. But yeah the pal_*() functions from {scales} are function factories whose results are valid input for the palette arguments in ggplot2.

teunbrand avatar Apr 04 '24 07:04 teunbrand