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)
The levels of "factor_var" being:
> levels(df$factor_var)
[1] "fac1" "fac2" "fac3"
I make a stacked area 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 "factor_var" ordered as per the levels seen before but the areas are not stacked in this same order. How can I produce an output with red at the bottom then grey then blue stacked on top as is the case in the legend?
(NB. This is the order I need (factor_var being an ordered variable), it is not just a case of matching the stacking to the legend order for aesthetic reasons.)
EDIT: Desired result shown below
SOLUTION !!
Reordering the dataframe is necessary to create the desired result:
newdata <- df[order(df$cont_var, df$factor_var),]
Many thanks for all your help.
You could 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 you plot:
# 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's 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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With