如何将我的图例组织成小组? [英] How can I organize my legend into subgroups?
问题描述
我的条形图的图例当前在一个长列表中列出了该图中的所有项目.我希望每个列都有图例组.
The legend for my bar graph currently lists all the items in the graph in one long list. I would like to have the legend group itself by each column.
列数是动态的,因此图例必须能够进行相应的调整.
The number of columns is dynamic so the legend must be able to adjust accordingly.
library("phyloseq"); packageVersion("phyloseq")
library(ggplot2)
library(scales)
data("GlobalPatterns")
TopNOTUs <- names(sort(taxa_sums(GlobalPatterns), TRUE)[1:50])
gp.ch <- prune_species(TopNOTUs, GlobalPatterns)
gp.ch = subset_taxa(gp.ch, Genus != "NA")
mdf = psmelt(gp.ch)
# Create a ggplot similar to
library("ggplot2")
mdf$group <- paste0(mdf$Phylum, "-", mdf$Genus, sep = "")
colours <-ColourPalleteMulti(mdf, "Phylum", "Genus")
# Plot resultss
ggplot(mdf, aes(Phylum)) +
geom_bar(aes(fill = group), colour = "grey", position = "stack")
现在,图例将打印项目:
Right now the legend prints the items:
放线菌-双歧杆菌
罗氏放线菌
细菌杆菌-阿利斯提普斯
Bacteriodetes-Alistipes
拟杆菌-拟杆菌
...
我要打印:
放线菌
-双歧杆菌
-Rothia
细菌杆菌
-Alistipes
-Alistipes
-拟杆菌
...
推荐答案
这很容易理解,但可能对您有用.首先,使用mtcars
数据集,将哑行添加到表示分组的数据中,然后为每个分组和组件类别分配一个因子级别.最后,我修改了图例中的Alpha,以便分组标题具有透明的颜色并看上去是隐藏的.
This is hacky but might work for you. First, using mtcars
dataset, I add dummy rows to the data representing the groupings, then assign a factor level to each of the groupings and component categories. Finally, I hack the alpha in the legend so that grouping headers have transparent colors and look hidden.
# Fake data sample
library(tidyverse)
cars_sample <- mtcars %>%
rownames_to_column(var = "name") %>%
mutate(make = word(name, end = 1),
model = word(name, start = 2, end = -1)) %>%
filter(make %in% c("Mazda", "Merc", "Hornet")) %>%
select(name, make, model, mpg, wt)
# Add rows for groups and make a factor for each group and each component
cars_sample_fct <- cars_sample %>%
bind_rows( cars_sample %>% count(make) %>% mutate(model = make, name = "")) %>%
arrange(make, name) %>%
mutate(name_fct = fct_inorder(if_else(name == "", make, paste0("- ", model))))
# Plot with transparent grouping legend labels
ggplot(cars_sample_fct, aes(wt, mpg, color = name_fct)) +
geom_point() +
scale_color_discrete(name = "Car") +
guides(color = guide_legend(
override.aes = list(size = 5,
alpha = cars_sample_fct$name != "")))
这篇关于如何将我的图例组织成小组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!