简体   繁体   中英

How to change the position of stacked stacked bar chart in ggplot in R?

I want to reverse the position of my stacked bar chart, however I couldn't make it even I follow some instruction given by other people in Stack Overflow. I want to make the N.Probability at the bottom and P.Probability on top (refer to the photo attached below).

在此处输入图片说明

library(ggplot2)

Month <- c("Aug", "Sep", "Oct")
P.Probability <- c(0.5, 0.6, 0.6)
N.Probability <- 1-P.Probability

dtf2 <- data.frame(Month, N.Probability, P.Probability)

dtf2_long <- tidyr::gather(dtf2, type, Probability, -Month)

ggplot(dtf2_long, aes(x = Month, y = Probability, fill = type)) + 
  geom_bar(stat = "identity") + 
  geom_hline(yintercept=0)+
  theme(axis.title.y=element_blank(),
        axis.title.x=element_blank(),
        plot.title = element_text(hjust = 0.5),
        plot.subtitle = element_text(hjust = 0.5))+
  theme(panel.background = element_blank(),
        axis.ticks.x = element_blank()) +
  theme(axis.line.y = element_line(color="black", size = 0.5))+
  geom_text(data = dtf2_long %>% filter(type == "P.Probability"),
            aes(label = paste(Probability*100, "%"), vjust = ifelse(Probability >= 0, -0.5, 1.2)))+
  scale_y_continuous(labels=scales::percent)

Please see here Stack Overflow

Simply add geom_bar(stat = "identity", position = position_fill(reverse = TRUE))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM