首页 > 解决方案 > 是否有 R ggplot 函数可以用不同的变量/数据集填充条形图?

问题描述

我使用以下方法创建了以下条形图:

structure(list(variable = structure(1:3, .Label = c("count_B", 
"count_M", "count_T"), class = "factor"), value = c(10.7894136128261, 
5.99274994891311, 4.10457180326646)), row.names = c(NA, -3L), class = "data.frame")

ggplot(meltedMUSICC, aes(x = variable, y = value, width = 0.95)) + geom_bar(stat = "identity") + coord_flip()

在此处输入图像描述

我有另一个数据集,它通过每个变量的百分比或相对丰度(满分 1)来指定填充,它看起来像这样:

structure(list(phylum = structure(1:4, .Label = c("Acidobacteria", 
"Actinobacteria", "Alphaproteobacteria", "Amoebozoa"), class = "factor"), 
    count_T = c(0.2, 0.1, 0.5, 0.2), count_M = c(0.1, 0.1, 0.1, 
    0.7), count_B = c(0.4, 0.3, 0.2, 0.1)), class = "data.frame", row.names = c(NA, 
-4L))

是否有一个函数可以用来填充条形图,使其成为带有第二个数据集的堆叠条形图,对其着色并获得图例?

标签: rggplot2charts

解决方案


我认为您的问题在于如何汇总数据。我假设您的第一个数据框中的计数是您的第二个数据框中所有相对计数的总和。

编辑

感谢发布数据

    library(ggplot2)
    library(tidyverse)

    df <- structure(list(variable = structure(1:3, .Label = c("count_B", 
                                                              "count_M", "count_T"), class = "factor"), value = c(10.7894136128261, 
                                                                                                                  5.99274994891311, 4.10457180326646)), row.names = c(NA, -3L), class = "data.frame")

    df2 <- structure(list(phylum = structure(1:4, .Label = c("Acidobacteria", 
                                                      "Actinobacteria", "Alphaproteobacteria", "Amoebozoa"), class = "factor"), 
                   count_T = c(0.2, 0.1, 0.5, 0.2), count_M = c(0.1, 0.1, 0.1, 
                                                                0.7), count_B = c(0.4, 0.3, 0.2, 0.1)), class = "data.frame", row.names = c(NA, 
                                                                                                                                            -4L))

    df3 <- df2 %>% pivot_longer(cols = -phylum) %>% 
      left_join(df, by = c("name" = "variable")) %>% 
      mutate(new_count = value.x*value.y)
    #> Warning: Column `name`/`variable` joining character vector and factor,
    #> coercing into character vector

    ggplot(df3, aes(x = name, y = new_count)) + geom_bar(stat = "identity", aes(fill = phylum))

reprex 包(v0.3.0)于 2020 年 2 月 27 日创建


推荐阅读