Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change stacking order in ggplot stacked area graph

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: enter image description here

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

enter image description here

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.

like image 934
user2568648 Avatar asked Feb 10 '23 13:02

user2568648


1 Answers

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:

enter image description here


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:

enter image description here

like image 101
Jaap Avatar answered Feb 12 '23 04:02

Jaap