Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 axis: how to combine scale_x_reverse with scale_x_continous

Tags:

r

ggplot2

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

like image 220
Rrrrrrrrrrr Avatar asked Aug 31 '17 17:08

Rrrrrrrrrrr


2 Answers

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")
    )
like image 86
davechilders Avatar answered Oct 19 '22 05:10

davechilders


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")
    )
like image 1
MS Berends Avatar answered Oct 19 '22 06:10

MS Berends