有時繪圖伯复,存在很多分類層次,需要用顏色邢笙,大小啸如,線條類型來逐級區(qū)分,但是造成圖例太多的情況氮惯,需要合并同類項叮雳。在網(wǎng)上找到了答案https://stackoverflow.com/questions/37140266/how-to-merge-color-line-style-and-shape-legends-in-ggplot
以下示例基于自己的數(shù)據(jù)
先上圖
- 加載工具包
library(reshape2)
library(dplyr)
library(phyloseq)
library(ggpubr)
- 加載整理數(shù)據(jù)
load('../01_filter_and_rarefy_Bacteria/.RData')
remove(physeq)
sample_variables(rarefy)
rarefy = subset_samples(rarefy, NP<100&EC<2000&CN<150& (!Sequencing_ID_16s_18s%in% c('M24','M12','M30')))
map = data.frame(sample_data(rarefy))
map = mutate(map,Latitude = abs(Latitude),
group = case_when(Vegetation == 'Forest'~ 'Forest', TRUE ~ 'NonForest'))
map$group = as.factor(map$group)
- 新建向量存儲變量組合
envs = c('Latitude', "Elevation", "Slope", # geologic
"MAT", "AI", # climate
"Plant_cover", # plant
"pH", "EC", "Clay_silt", 'WHC','TP') # soil
funs = c("BG","PHOS","NAG","Rb","PO4","NO3", "NH4", 'NPP', 'ORC')
- 計算多樣性
richness = estimate_richness(rarefy, measures="Observed")
rownames(richness) == map$Global_Atlas_Order
map$Bacteria_richness = richness$Observed
map$Global_Atlas_Order = NULL
- 整理數(shù)據(jù)
env_div = map[c(envs, 'group', 'Plant_richness','Bacteria_richness')] %>%
mutate(Plant_richness = scale(Plant_richness), Bacteria_richness = scale(Bacteria_richness)) %>%
melt(id.vars = c('group', 'Plant_richness','Bacteria_richness'),
variable.name = 'ENV', value.name ='value') %>%
melt(id.vars = c('ENV','value','group'), variable.name = 'Organism', value.name = 'diversity') %>%
mutate(Organism = case_when(Organism == 'Plant_richness'~'Plant', TRUE ~ 'Bacteria')) %>%
mutate(labels = paste(group, Organism))
env_div$labels = factor(env_div$labels,
levels = c('Forest Plant','Forest Bacteria',
'NonForest Plant','NonForest Bacteria'))
env_div$ENV = gsub('_',' ',env_div$ENV)
- 繪圖
#獲取ggplot2的默認(rèn)顏色
library(scales)
show_col(hue_pal()(2))
env_div_p = ggplot(env_div, aes(value, diversity, color = labels, linetype = group)) +
facet_wrap(ENV~.,scales = 'free', ncol = 4, strip.position = 'bottom') +
geom_smooth(method = 'loess', span = 1, formula = y~x, se = F) +
guides(color = guide_legend(override.aes = list(linetype = c(1,1,2,2))),
linetype = 'none') +
scale_color_manual(values = rep(rev(hue_pal()(2)), 2)) +
labs(x = NULL, y = 'diversity (scaled)', color = NULL) +
theme_classic() +
theme(axis.title = element_text(color = 'black'),
axis.text = element_text(color = 'black'),
legend.text = element_text(color = 'black'),
legend.position = c(0.9,0.1),
legend.key.width = unit(1,'cm'),
strip.text = element_text(color = 'black'),
strip.background = element_blank(),
strip.placement = 'outside')