Skip to content

Feature Request: Allow reversing discrete scales #3115

Closed
@billdenney

Description

@billdenney

In many scenarios across aesthetics (x, y, fill, colour, and probably anything discrete), it would help to have the option to reverse factor levels on a discrete axis.

What would you think of a PR for one of the options below?

However this is implemented, it would also propagate to a change in the scales package. I think that the simplest change would be to make a scales::reverse_trans_discrete() function, but I've not fully dived in to confirm that.

I think that the simplest and least invasive change would be to add a reverse argument to all the scale_*_discrete() and similar categorical functions (e.g. scale_colour_hue() and scale_colour_viridis_d()). With reverse=TRUE, scales::reverse_trans_discrete() would be used.

library(ggplot2)
d <-
  data.frame(
    x_fac=factor(LETTERS[1:3]),
    y=1:3
  )
ggplot(d, aes(x=x_fac, y=y)) +
  geom_point()

ggplot(d, aes(x=x_fac, y=y)) +
  geom_point() +
  scale_x_reverse()
#> Warning in Ops.factor(x): '-' not meaningful for factors
#> Warning: Transformation introduced infinite values in continuous x-axis
#> Error: Discrete value supplied to continuous scale
# Thanks @jennybc! (from https://gist.github.com/jennybc/6f3fa527b915b920fdd5)
ggplot(d, aes(x=x_fac, y=y)) +
  geom_point() +
  scale_x_discrete(limits=rev(levels(d$x_fac)))

# Implementation option: scale_x_discrete and similar gains a `reverse`
# argument which defaults to `FALSE`
ggplot(d, aes(x=x_fac, y=y)) +
  geom_point() +
  scale_x_discrete(reverse=TRUE)
#> Error in discrete_scale(c("x", "xmin", "xmax", "xend"), "position_d", : unused argument (reverse = TRUE)

Created on 2019-02-03 by the reprex package (v0.2.0).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions