我在ggplot2中有一个堆积条形图,所有列总和为1.但是,每个堆栈中有63个部分,如果我在图中显示所有图例键,则会占用太多空格。我怎样才能显示最大8个比例的图例键,并将所有其他键放到“其他”?
My dataset in pastebin.com,我假设您将其输入为Dataset
。
ggplot(Dataset,aes(Level,Value,group=Taxon,fill=Taxon))+geom_bar(stat="identity")+facet_wrap(~Site)+
scale_fill_manual(values = diverge_hcl(63))+
ylab("")+
theme(
legend.position = "none"
)
我想要一个这样的传奇:
答案 0 :(得分:1)
假设我们从输入文件Dataset0
Taxon_data.txt
开始
library(colorspace)
library(RColorBrewer)
library(magrittr)
library(tidyverse)
Dataset0 <- dget("Taxon_data.txt")
# Clean up labels: keep only the text after the underscore _
Dataset0 %<>%
mutate(Taxon = sub('.*\\_', '', Taxon)) %>%
arrange(desc(Value))
# Create new factor "Tax" sorted by Value
Dataset0 %<>%
mutate(Site = factor(Site)) %>%
mutate(Tax = factor(Taxon, levels = unique(Taxon[order(-Value)])))
# Create labels for Legend
myLabel <- c(levels(Dataset0$Tax)[1:8], "Others",
paste0("Others", 1:(length(unique(Dataset0$Tax)) - 9)))
myLabel
# Set myLabel for Tax, create new Dataset data frame
Dataset <- Dataset0 %>%
mutate(Tax = factor(Tax, labels = myLabel))
# Setup colors
myColor <- c(brewer.pal(8, "Dark2"),
rep("lightblue3", length(unique(Dataset$Tax)) - 8))
# Plot
g1 <- ggplot(Dataset, aes(Level, Value, group=Tax, fill=Tax)) +
geom_bar(stat = "identity") +
facet_wrap(~ Site) +
scale_fill_manual("Legend",
breaks = c(levels(Dataset$Tax)[1:8], "Others"),
values = myColor) +
ylab("") +
scale_x_discrete(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
theme_minimal(base_size = 14)
g1
由reprex package(v0.2.0)创建于2018-03-14。