Pauline V. Pauline V. - 6 days ago 6
R Question

Colour scale inversion with new version of ggplot

I have a quality process where I need to export the exact same graphs over time. I mainly use the stacked bar chart from ggplot2 which is highly sufficiant for me. Recently, I updated my ggplot2 version to ggplot2 2.2.0 and I cannont find a way to reproduce my previous graphs.

Here is my code :

DF1=data.frame(Rank=rep(1:4,3),variable=rep(c("F1","F2","F3"),each=4),value=c(500,400,300,200,250,100,155,90,50,30,100,10))
library(ggplot2)
ggplot(DF1, aes(x = Rank, y = value, fill = variable)) + geom_bar(stat = "identity")


In the previous version of ggplot2, this code generated a graph where F1 was in pink, F2 was in green and F3 in blue. This is still the case but now the pink part is at the top of the bar (see image below)

Difference between the two graphs

I tried to reverse order of the variable factor, but now F1 is in blue etc which is not what I want neither.

DF1$variable=factor(DF1$variable,levels=rev(levels(DF1$variable)))
ggplot(DF1, aes(x = Rank, y = value, fill = variable)) + geom_bar(stat = "identity")


enter image description here

Do you have any idea how I can find my good old garph back ? (going back to the previous version is not a viable version in a long term perspective)

Answer

You could set reverse = TRUE in position_stack to reverse the default stacking order (see ?position_stack).

ggplot(DF1, aes(x = Rank, y = value, fill = variable)) +
  geom_bar(stat = "identity", position = position_stack(reverse = TRUE))

Which gives:

enter image description here

Comments