【问题标题】:Merge multiple bar plots using ggplot2使用 ggplot2 合并多个条形图
【发布时间】:2022-01-23 20:20:25
【问题描述】:

我有 3 个这样的数据集:


animal  percentage 
bear       25
lion       87
tiger      14


shape     percentage
circle     17
square     67


color     percentage
red        48
blue       5
green      11

我想使用 ggplot2 将它们全部绘制在同一个条形图上,在 y 轴上显示百分比,然后在 x 轴上显示:


bear   lion    tiger           circle     square             red    blue   green
      animal                         shape                          color

我知道如何单独制作图表,但我似乎无法将它们放在同一个图表上,我尝试了 facet_wrap,但无法让它工作。我还尝试使用 cbind 将所有内容放在一个数据集中,但由于它们的长度不同,它也不起作用。任何见解都会很棒!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    问题在于您的数据不是同质的。您可以将其重塑为具有相同的列结构,然后您可以合并数据并绘制它。

    library(ggplot2)
    
    
    dat1 <- data.frame(animal = c("bear", "lion", "tiger"),
                       percentage = c(25, 87, 14))
    dat2 <- data.frame(shape = c("circle", "square"),
                       percentage = c(17, 67))
    dat3 <- data.frame(color = c("red", "blue", "green"),
                       percentage = c(48, 5, 11))
    
    # Combining all the data
    all <- list(dat1, dat2, dat3)
    all <- lapply(all, function(dat) {
      dat$type <- colnames(dat)[1]
      colnames(dat)[1] <- "variable"
      dat
    })
    all <- do.call(rbind, all)
    
    ggplot(all, aes(variable, percentage)) +
      geom_col() +
      facet_wrap(~ type, scales = "free_x")
    

    reprex package (v2.0.1) 于 2021 年 12 月 22 日创建

    【讨论】:

    • 你可以通过设置facet_grid(switch = 'both')theme(strip.placement = 'outside', strip.background = element_blank())来进一步匹配OP想要的输出
    • 您可以选择data.table::rbindlist(...),而不是使用do.call(rbind, ...),这样会更快
    • @jdobres,是的,对于facet_wrap(),那将是strip.position = "bottom",但确实可以提供帮助。 @Wietse de Vries,是的,我喜欢这个功能,但我通常认为人们(包括我自己)试图限制运行一段代码所需的包数量。
    • @teunbrand 我会抓住任何机会让人们安装data.table 哈哈,拥有大量数据集的人要求dplyr 解决方案的次数是惊人的
    • 确实!如果您更喜欢 tidyverse 语法,可以使用 {dtplyr},但 data.table 的性能很好
    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 2013-12-02
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 2021-04-24
    相关资源
    最近更新 更多