简体   繁体   中英

How to combine 2 variables in bar chart by using ggplot in R studio?

I'm trying to plot a multivariate bar chart by using ggplot such that one bar consist of two different colour which represent two variables instead of comparing the 2 variables side by side. The 2 variables will be positive probability ( P.Probability ) and negative probability ( N.Probability ).

The code below is my data. I'm only able to include P.Probability in the code but I want both P.Probability and N.Probability to be included in the graph as I mentioned above.

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

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

ggplot(dtf2, aes(x = Month, y = P.Probability)) + 
  geom_bar(stat = "identity") + 
  geom_hline(yintercept=0)+
  theme(axis.title.y=element_blank(),
        axis.title.x=element_blank(),
        legend.position = "none",
        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(aes(label = paste(P.Probability*100, "%"), vjust = ifelse(P.Probability >= 0, -0.5, 1.2)))+
  scale_y_continuous(labels=scales::percent)

The diagram attached below is the graph that I want. I hope the N.Probability will be the blue colour as the bottom and the P.Probability will be the red colour on top.

在此处输入图片说明

I'd suggest gathering into long format so you can map the type of probability to fill color.

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(),
        legend.position = "none",
        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)

在此处输入图片说明

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