6

for my graph

 ggplot(data=data, x=x, y=y, fill=factor(c)+ geom_path()+geom_errorbar()+   geom_point() 

I would like to plot the y.axis reverse, using

scale_y_reverse()

while define its limits, breaks, labels and expands.

usually I use:

scale_y_continuous(limits=c(x,y), breaks=c(x,y,z), labels=c(x,y,z), expand(x,y))

well, apparently

scale_y_reverse()

and scale_y_continous() are somehow considered as the same code!? As I get an Error, saying:

"Scale for 'y' is already present. Adding another scale for 'y', which will replace the existing scale."

I found a post saying that it is possible to combine the two commands, thus I tried:

scale_y_reverse(limits=c(x,y), breaks=c(x,y,z), labels=c(x,y,z), expand(x,y))

which doesn't work either.

I am sure that there has to be a way, and as usual I suppose it is very simple.. once you know.

I hope someone know how to solve this.

Kind Regards

Rrrrrrrrrrr
  • 95
  • 1
  • 9

2 Answers2

7

Each aesthetic property of the graph (y-axis, x-axis, color, etc.) only accepts a single scale. If you specify 2 scales, e.g. scale_y_continuous() followed by scale_y_reverse(), the first scale is overridden.

You can specify limits, breaks, and labels in scale_y_reverse() and just omit scale_y_continuous().

Example:

d <- data.frame(a = 1:10, b = 10:1)

ggplot(d, aes(x = a, y = b)) +
  geom_point() +
  scale_y_reverse(
    limits = c(15, 0), 
    breaks = seq(15, 0, by = -3),
    labels = c("hi", "there", "nice", "to", "meet", "you")
    )
davechilders
  • 8,693
  • 2
  • 18
  • 18
  • Thank you @DMC for the fast and especially nice response! – Rrrrrrrrrrr Sep 01 '17 at 09:34
  • Is there any option to provide another scale transformation *on top* like "log10"? If I add the "trans=x" argument it conflicts with the inherited trans of scale_y_reverse.. – Tapper Nov 19 '18 at 17:08
  • It is answered at another question (you need to write your own function for that): https://stackoverflow.com/a/11054781/620410 – Tapper Nov 19 '18 at 17:11
1

If you want to keep scale_y_continuous() for more easy argument typing, you can use it instead of scale_y_reverse() by setting the trans parameter:

d <- data.frame(a = 1:10, b = 10:1)

ggplot(d, aes(x = a, y = b)) +
  geom_point() +
  scale_y_continuous(
    trans = scales::reverse_trans(), # <- this one is your solution :)
    limits = c(15, 0), 
    breaks = seq(15, 0, by = -3),
    labels = c("hi", "there", "nice", "to", "meet", "you")
    )
MS Berends
  • 4,489
  • 1
  • 40
  • 53