【问题标题】:Display a summary bar next to the individual categories of a stacked barchart在堆叠条形图的各个类别旁边显示摘要栏
【发布时间】:2019-11-29 10:57:54
【问题描述】:

使用以下代码,我可以在下面创建图表:

library(ggplot2)
ds <- as.data.frame(mtcars)
 ds$gear <- as.factor(ds$gear)
 ds$carb <- as.factor(ds$carb)
d1 <- ds[ds$carb %in% c("1","2","3"),]

ggplot(d1, aes(fill=gear, x=carb)) +
 coord_flip() +
 geom_bar(position=position_fill(reverse=TRUE), width=0.7)

我现在如何在顶部创建一个额外的栏,以提供三个组的摘要图? 理想情况下,它应该在同一个情节中,而不是在单独的情节中

【问题讨论】:

    标签: r ggplot2 bar-chart stacked


    【解决方案1】:

    在同一图中获得附加条的最简单方法是将数据附加到原始数据集:

    # Create new category "Summary" and combine with the original dataset
    pd <- rbind(
      d1[, c("gear", "carb")],
      data.frame(carb = "Summary", gear = d1$gear)
    )
    # Plot combined dataset
    ggplot(pd, aes(carb, fill = gear)) +
      coord_flip() +
      geom_bar(position = position_fill(reverse = TRUE))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      • 2021-06-17
      • 2012-10-21
      相关资源
      最近更新 更多