Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to reverse the ordering of a scale inside an aes() inside a geom()?

Tags:

r

ggplot2

I've found many examples describing the assignment of alpha when in a ggplot2 line like so:

scale_alpha( variable, trans = reverse)

ref

However, is there a method to simply invert the scale in aes() inside the geom_*()?

Something like:

geom_point(aes(colour=variableA, alpha=REVERSE(variableB))
like image 417
DaveRGP Avatar asked Nov 22 '22 10:11

DaveRGP


1 Answers

(This is a very old question, but I had the same issue and couldn't find an answer. The previous solution by hugh-allan is, as indicated in the Edit note, producing an incorrect legend.)

The settings of the scale should really be in the scale_alpha* parameter. That's where you manage this. The geoms are used for adding the data or setting a style for all points, not tuning a specific scale (otherwise, it would need to be inside the aes() mapping).

To be clear, there are two options in current versions of ggplot2 (using version 3.3.5):

tibble(x = 1:10, y = 1) %>%
  ggplot(aes(x, y, alpha = x) +
  geom_point(size = 5) +
  scale_alpha(trans = reverse_trans())

or, probably more in line with current ggplot documentation:

  scale_alpha(range = c(1, 0.1))

i.e., reversing the range of the alpha scale (the default is range = c(1, 0.1)).

like image 139
iNyar Avatar answered Jun 11 '23 03:06

iNyar