【问题标题】:How to combine 2 variables in bar chart by using ggplot in R studio?如何在 R studio 中使用 ggplot 在条形图中组合 2 个变量?
【发布时间】:2019-08-15 06:11:03
【问题描述】:

我正在尝试使用 ggplot 绘制一个多元条形图,这样一个条形图由两种不同的颜色组成,它们代表两个变量,而不是并排比较两个变量。这两个变量将是正概率 (P.Probability) 和负概率 (N.Probability)。

下面的代码是我的数据。我只能在代码中包含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)

下面的图表是我想要的图表。我希望N.Probability 是底部的蓝色,P.Probability 是顶部的红色。

【问题讨论】:

    标签: r variables ggplot2 bar-chart


    【解决方案1】:

    我建议收集成长格式,以便您可以映射概率类型以填充颜色。

    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)
    

    【讨论】:

    • 感谢您的回复!它对我有用:) 但是,我应该怎么做才能使底部的 N.Probability 和顶部的 P.Probability 出现,您显示的图表看起来就像我想要的那样倒置。此外,是否可以将颜色更改为 N.Probability 为黑色而 P.Probability 为红色?谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多