Stacked bar graph in R: re-ordering the data

49 views Asked by At

I've produced a bar graph, however I want the data to be switched. I want the blue area (the live cells) on the bottom and the dead cells on the top. I tried reorder, reordering it by making it a factor but it all didn't work.

Who can help me?

Code I have now:

b_stack1<-ggplot(Stack1, aes(x=Condition, y=N, fill=Type)) + 
  geom_bar(aes(fill = Type), stat="identity", position="stack", color="black") +
  scale_fill_manual(values=c("lightblue","grey")) +
  theme_bw() + theme(legend.position="right", axis.title.x = element_blank())

Graph I have now: Graph

3

There are 3 answers

0
Kim On BEST ANSWER
    `install.packages("forcats") 
b_stack1<-ggplot(Stack1, aes(x=Condition, y=N, fill = forcats::fct_rev(Type))) + 

geom_bar(stat="identity", position="stack", color="black") + scale_fill_manual(values=c("lightblue","grey"))`

Forcats did the trick

0
Bruno On
library(forcats)

b_stack1<-ggplot(Stack1, aes(x=Condition, y=N, fill=fct_shift(Type))) + 
  geom_bar(aes(fill = Type), stat="identity", position="stack", color="black") +
  scale_fill_manual(values=c("lightblue","grey")) +
  theme_bw() + theme(legend.position="right", axis.title.x = element_blank())
0
Blue050205 On

Have you tried position_stack(reverse = TRUE)?

b_stack1<-ggplot(Stack1, aes(x=Condition, y=N, fill=Type)) + 
  geom_bar(aes(fill = Type), stat="identity", position = position_stack(reverse = TRUE)), color="black") +
  scale_fill_manual(values=c("lightblue","grey")) +
  theme_bw() + theme(legend.position="right", axis.title.x = element_blank())