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:
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
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.
source to share
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:
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:
source to share