ggplot2 icon indicating copy to clipboard operation
ggplot2 copied to clipboard

Discrete secondary axes

Open teunbrand opened this issue 6 months ago • 2 comments

This PR aims to fix #3171.

Briefly, it adds a sec.axis option for scale_{x/y}_discrete().

For context: The secondary axis system is not ideal. We have tried to move that functionality to guides in #5410, but it becomes too complicated. Because it doesn't seem viable to handle this functionality in guides, I think it is time to implement secondary axes for discrete scales.

In some more detail: It currently only accepts identity transformations, as it just doesn't make sense to me why one would transform a discrete axis. This also means that dup_axis() should be preferred to sec_axis() for discrete scales. Breaks can be given as numeric that can take arbitrary positions, or as discrete breaks that can take one of the limits values. For discrete scales, breaks are mapped early on in AxisSecondary$break_info().

An example plot with relabelling the x-axis and numeric positions in the y-axis:

devtools::load_all("~/packages/ggplot2")
#> ℹ Loading ggplot2

data <- data.frame(x = c("A", "B", "C"), y = c("D", "E", "F"))
ggplot(data, aes(x, y)) +
  geom_point() +
  scale_x_discrete(sec.axis = dup_axis(
    labels = c("foo", "bar", "baz"),
    name = "Secondary x-axis"
  )) +
  scale_y_discrete(sec.axis = dup_axis(
    breaks = c(1.5, 2.5), labels = c("grault", "garply"),
    name = "Secondary y-axis"
  ))

Created on 2024-01-02 with reprex v2.0.2

teunbrand avatar Jan 02 '24 11:01 teunbrand

Hi, many thanks for implementing this! I see in preparation the next ggplot2 release, is it going to make it in time?

llrs avatar Jan 29 '24 14:01 llrs

I'm afraid this will not be included in the upcoming release.

teunbrand avatar Jan 30 '24 08:01 teunbrand