How can I organize my legend into subgroups?

烂漫一生 提交于 2020-06-26 12:27:19

问题


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:

Actinobacteria-Bifidobacterium

Actinobacteria-Rothia

Bacteriodetes-Alistipes

Bacteriodetes-Bacteroides

...

I would like it to print:

Actinobacteria

-Bifidobacterium

-Rothia

Bacteriodetes

-Alistipes

-Bacteroides

...


回答1:


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



来源:https://stackoverflow.com/questions/56064662/how-can-i-organize-my-legend-into-subgroups

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!