r - 是否有 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))
是否有一个函数可以用来填充条形图,使其成为带有第二个数据集的堆叠条形图,对其着色并获得图例?
解决方案
我认为您的问题在于如何汇总数据。我假设您的第一个数据框中的计数是您的第二个数据框中所有相对计数的总和。
编辑
感谢发布数据
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 日创建
推荐阅读
- outlook - 适用于仅命令加载项的 Office 365 清单
- javascript - 如何遍历 Typescript 中的地图:for...in?为了……的?为每个?
- powershell - 使用 Powershell 部署 SSIS - 缺少 DMF
- datetime - 如何判断给定的 NaiveDateTime(加上像“US/Mountain”这样的时区)是否在 Elixir 的过去?
- mongodb - 如何使用驱动程序在 MongoDB 中进行文档版本控制
- json - Postgresql 如何在 jsonb 中求和(值)并按月份对它们进行分组?
- javascript - 如何切换开/关切换功能?
- python - SimpleImputer ValueError
- sql - 在 Postgres 中检查用户的登录权限
- google-apps-script - 谷歌脚本只导入少数带有脚本的列