【问题标题】:Creating a side by side bar plot with 1 continuous variable and 2 factor variables (one for stacking and the other for grouping bars)创建具有 1 个连续变量和 2 个因子变量的并排条形图(一个用于堆叠,另一个用于分组条形图)
【发布时间】:2020-07-20 12:12:43
【问题描述】:

我有一个长格式的数据框如下(示例):

QuarterPeriod <- c(rep("2011_Q1",4), rep("2011_Q2",4), 
                   rep("2011_Q3",4), rep("2011_Q4",4), 
                   rep("2012_Q1",4), rep("2012_Q2",4))
HFGroup <- c(rep(c("Phase I","Phase II"),12))
QuantGroup <- c(rep(c(rep("Declared", 2), 
                      rep("Verified", 2)),6))
Values <- c(sample.int(25:100, 24))

df <- as.data.frame(cbind(QuarterPeriod, HFGroup,
                          QuantGroup,Values))

我有以下代码来创建 2 个条形图,其中一个因子变量用于分面,另一个用于对图中的条形图进行分组:

require(ggplot2)
ggplot(data=df,
       aes(x=QuarterPeriod, y= Values,
           fill=QuantGroup)) +
  geom_bar(stat="identity", position=position_dodge()) +
  facet_wrap(~HFGroup)

我想要 1 个图,而不是使用分面来获得 2 个图,其中 2 个因子变量(QuantGroup 和 HFGroup)用于:

  1. 堆叠(HFGroup):在第一阶段的顶部有第二阶段
  2. 分组 (QuantGroup):并排绘制同一季度的声明和验证数据。

最后,比如 2011_Q1,应该有 2 个条形图(一个用于声明数据,另一个用于验证数据),但每个条形图应该显示第一阶段和第二阶段堆叠在一起。

【问题讨论】:

    标签: r ggplot2 bar-chart


    【解决方案1】:

    您不能在条形图上同时拥有position_dodgeposition_stack,因此您需要发挥创意。您可以通过按季度而不是HFGroup 进行刻面,并通过HFGroup 填充来获得您正在寻找的效果。然后,您将 QuantGroup 设为您的 x 轴。这为您提供了每个季度的 2 列堆叠条。然后,您只需调整刻面,使它们看起来不像刻面,方法是将它们的间距减小到零并将条带放在底部:

    ggplot(df, aes(QuantGroup, Values, fill = HFGroup)) +
      geom_col() +
      facet_grid( ~ QuarterPeriod, switch = "x") +
      xlab("Quant Group by Quarter") +
      theme(panel.spacing    = unit(0, "points"),
            strip.background = element_blank(),
            strip.placement  = "outside")
    

    【讨论】:

    • 谢谢,这正是我想要的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 2017-05-28
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多