R plotresearchIMP research

R语言~图例中的合并同类项

2022-07-27  本文已影响0人  Oodelay

有时绘图,存在很多分类层次,需要用颜色,大小,线条类型来逐级区分,但是造成图例太多的情况,需要合并同类项。在网上找到了答案https://stackoverflow.com/questions/37140266/how-to-merge-color-line-style-and-shape-legends-in-ggplot

以下示例基于自己的数据

先上图

  1. 加载工具包
library(reshape2)
library(dplyr)
library(phyloseq)
library(ggpubr)
  1. 加载整理数据
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)
  1. 新建向量存储变量组合
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')
  1. 计算多样性
richness = estimate_richness(rarefy, measures="Observed")
rownames(richness) == map$Global_Atlas_Order
map$Bacteria_richness = richness$Observed
map$Global_Atlas_Order = NULL
  1. 整理数据
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)
  1. 绘图
#获取ggplot2的默认颜色
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')
上一篇下一篇

猜你喜欢

热点阅读