Changing the stacking order in the ggplot stacked area

I have the following data:

df <- as.data.frame(c(rep(1,3),rep(2,3),rep(3,3)))
names(df) <- "cont_var"
df$factor_var <- as.factor(rep(c("fac1","fac2","fac3"),3))
df$prop <- c(10,20,70,20,30,50,25,40,35)

      

"Factor_var" levels:

> levels(df$factor_var)
[1] "fac1" "fac2" "fac3"

      

I am making a region-wise plot using the following:

library(ggplot)
ggplot(df, aes(x=cont_var, y=prop, fill=factor_var)) +
  geom_area(colour="black",size=.2, alpha=.8) +
  scale_fill_manual(values=c("blue", "grey", "red"))

      

which returns the following result: enter image description here

The legend shows that "factor_var" is ordered by the levels previously visible, but the regions do not fit in the same order. How can I create an exit with red at the bottom and then gray and then blue just like in the legend?

(NB. This is the order I need (factor_var is an ordered variable), this is not just a case where the stacking matches the order of the legend for aesthetic reasons.)

EDIT: The desired output is shown below

enter image description here

DECISION!

To create the desired result, you need to change the order of the data:

newdata <- df[order(df$cont_var, df$factor_var),]

      

Many thanks for your help.

+3


source to share


2 answers


You can change the order of your legend by adding guides(fill = guide_legend(reverse=TRUE))

to your code:

ggplot(dat, aes(x=cont_var, y=prop, fill=factor_var)) +
  geom_area(colour="black",size=.2, alpha=.8) +
  scale_fill_manual(values=c("blue", "grey", "red")) +
  guides(fill = guide_legend(reverse=TRUE))

      

this gives:

enter image description here




Alternatively, you can set the factor levels before plotting:

# manually ordering the factor levels
dat$factor_var2 <- factor(dat$factor_var, levels=c("fac3","fac2","fac1"))
# automatcally ordering the factor levels (copied from Jakub P answer)
dat$factor_var2 <- factor(dat$factor_var, sort(unique(dat$factor_var), decreasing = TRUE))

ggplot(dat, aes(x=cont_var, y=prop, fill=factor_var2)) +
  geom_area(colour="black",size=.2, alpha=.8) +
  scale_fill_manual(values=c("blue", "grey", "red"))

      

this gives:

enter image description here

+5


source


Will this work?

df$factor_var <- rep(c("fac1","fac2","fac3"),3)
df$factor_var <- factor(df$factor_var, sort(unique(df$factor_var), decreasing = T))

      



In the test data you suggested, this produces a constant result when fac1 is red and at the bottom, etc.

+1


source







All Articles