如何在R中的ggplot中更改堆叠堆叠条形图的位置?

时间:2019-08-16 09:49:19

标签: r ggplot2 stack bar-chart

我想颠倒堆积条形图的位置,但是即使我遵循了stackoverflow中其他人的某些指示,也无法做到。我想在底部制作N.Probability,在顶部制作P.Probability(请参阅下面的照片)。请给我一些建议,谢谢!

enter image description here

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)

任何帮助将不胜感激! :)

1 个答案:

答案 0 :(得分:1)

请在此处查看Stack Overflow

只需添加geom_bar(stat = "identity", position = position_fill(reverse = TRUE))