【发布时间】:2019-05-13 22:52:00
【问题描述】:
我有一些代码以堆叠条形图的形式显示门的丰度以及该门内的属。我编辑了代码,使所有 NA 元素出现在每个栏的顶部,而更丰富的元素出现在底部,但是,这抛弃了我的调色板,该调色板根据门组分配颜色,并在该组内按字母.例如,拟杆菌门被指定为蓝色,门内的每个属按字母顺序被指定为蓝色阴影。
我相信我可以更改 levs 变量以按字母顺序对元素进行排序并按门分组,但我还没有找到一种方法来做到这一点。然而,目前,levs 变量按丰度对元素进行排序,这是我想要保留的。
#makes color pallete
ColourPalleteMulti <- function(df, group, subgroup){
# Find how many colour categories to create and the number of colours in each
categories <- aggregate(as.formula(paste(subgroup, group, sep="~" )), df, function(x) length(unique(x)))
category.start <- (scales::hue_pal(l = 100)(nrow(categories))) # Set the top of the colour pallete
category.end <- (scales::hue_pal(l = 40)(nrow(categories))) # set the bottom
# Build Colour pallette
colours <- unlist(lapply(1:nrow(categories),
function(i){
colorRampPalette(colors = c(category.start[i], category.end[i]))(categories[i,2])}))
return(colours)
}
library(tidyverse)
library("phyloseq"); packageVersion("phyloseq")
library(ggplot2)
library(scales)
library(RColorBrewer)
data("GlobalPatterns")
#filter phyloseq data
TopNOTUs <- names(sort(taxa_sums(GlobalPatterns), TRUE)[1:100])
gp.ch <- prune_species(TopNOTUs, GlobalPatterns)
#create dataframe
mdf = psmelt(gp.ch)
mdf$group <- paste0(mdf$Phylum, "-", mdf$Genus, sep = "")
#factor by abundance
levs <- names(sort(tapply(mdf$Abundance, mdf$Genus, sum)))
#load colors
colours <- ColourPalleteMulti(mdf, "Phylum", "Genus")
#put NA at the top
mdf %>%
mutate(Genus = fct_explicit_na(Genus, "NA"),
Genus = factor(Genus, levels = c("NA", levs))) %>%
#graph
ggplot(aes(Phylum)) +
geom_bar(aes(fill = Genus), colour = "grey", position = "stack") +
scale_fill_manual("Genus", values=c("#FFFFFF",colours)) +
ggtitle("Phylum and Genus Frequency") +
ylab("Frequency") +
theme(plot.title = element_text(hjust = 0.5))
运行此代码会显示一个条形图,其中的颜色位于奇怪的位置。理想情况下,图表中的每个条形都是原色,每个堆栈都是不同的颜色阴影。正确创建了调色板,但由于上述问题,颜色分配不正确。任何帮助表示赞赏!
【问题讨论】: