如何将我的图例分为几个小组?

时间:2019-05-09 17:29:24

标签: r ggplot2 legend

我的条形图的图例当前在一个长列表中列出了图中的所有项目。我希望每个列都有图例组。

列数是动态的,因此图例必须能够进行相应的调整。

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")

现在,图例将打印项目:

放线菌-双歧杆菌

罗氏放线菌

细菌杆菌属阿利斯皮斯

拟杆菌-拟杆菌

...

我要打印:

放线菌

-双歧杆菌

-Rothia

细菌杆菌

-Alistipes

-拟杆菌

...

1 个答案:

答案 0 :(得分:0)

这很骇人,但可能对您有用。首先,使用mtcars数据集,向表示分组的数据中添加虚拟行,然后为各个分组和组件类别分配一个因子级别。最后,我修改图例中的Alpha,以便分组标题具有透明的颜色并看上去是隐藏的。

# 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 != "")))

enter image description here