简体   繁体   English

如何通过在 R studio 中使用 ggplot 在条形图中组合 2 个变量?

[英]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.我正在尝试使用 ggplot 绘制多变量条形图,这样一个条形由两种不同的颜色组成,代表两个变量,而不是并排比较这两个变量。 The 2 variables will be positive probability ( P.Probability ) and negative probability ( N.Probability ).这两个变量将是正概率 ( P.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.我只能在代码中包含P.Probability但我希望P.ProbabilityN.Probability都包含在我上面提到的图表中。

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.我希望N.Probability将是底部的蓝色,而P.Probability将是顶部的红色。

在此处输入图片说明

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)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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