hello拷获,大家好芬迄,今天分享一個簡單的內(nèi)容磷支,我們實現(xiàn)下面的這張圖
參考文獻在
這張圖實現(xiàn)的箱線圖最岗,分面并注釋萎坷,好看的圖勝過千言萬語耳奕,我們來實現(xiàn)它僧著。
嵌套分面已經(jīng)有集成的R包了既绩,ggh4x包身辨,學(xué)習(xí)一下即可丐谋。
加載R包和數(shù)據(jù)
library(ggh4x)
library(ggplot2)
library(reshape2)
library(tidyverse)
####示例數(shù)據(jù)可以從文獻鏈接處下載
input = read.delim('示例數(shù)據(jù)',header = T)
head(input,3)
###寬轉(zhuǎn)長
df = melt(input,id.vars = c('Precursor','Dataset','Model'))
head(df,3)
###因子化排序
df$Model = factor(df$Model,levels = c('DeepPhospho','pDeep2','DeepMS2','MS2PIP'))
設(shè)置嵌套背景
設(shè)置一下填充色和邊框顏色
###背景
strip = strip_nested(background_x = elem_list_rect(fill = c(rep('grey',2),
rep(c('#F58840','#9AE66E'),2)),color = rep('white',6)))
基礎(chǔ)繪圖
這里使用expansion來擴展x軸煌珊,防止插入每個分面圖最后一列文字跑出去:
###繪圖
p = ggplot(df,aes(x = Model,y = value,fill = Model)) +
##誤差線
stat_boxplot(aes(x = Model,y = value),
geom = 'errorbar',width = 0.3) +
###箱線圖層
geom_boxplot(outlier.shape = NA 号俐, width = 0.5 ) +
theme_bw(base_size = 16) +
##主題調(diào)整
theme(panel.grid = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
legend.position = 'bottom') +
xlab('') + ylab('') +
ylim(-0.5,1) +
##自定義顏色
scale_fill_manual(values = c('#BFA2DB','#F58840','#CDF2CA','#9D9D9D'),
name = ' ') +
##x軸擴展
scale_x_discrete(expand = expansion(mult = c(0.2,0.3))) +
###嵌套分面
facet_nested(~Dataset + variable,scales = 'free_y',axes = 'all',
strip = strip)
p
統(tǒng)計數(shù)據(jù)
圖中的文本注釋為每個分組的數(shù)據(jù)的中位數(shù)及對應(yīng)的數(shù)量,我們需要統(tǒng)計一下:
循環(huán)統(tǒng)計
fin = list()
for (i in names(table(df$Model))){
tmp1 = df %>% filter(Model == i)
for (j in names(table(df$variable))){
tmp2 = tmp1 %>% filter(Dataset == k)
res = round(median(tmp3$value,na.rm = T),digits = 3)
n = round(length(tmp3$value),digits = 0)
fin[[paste(i,j,k,sep = ' ')]] <- c(n,res)
}
}
}
##整合數(shù)據(jù)
fin_res= fin %>% do.call('rbind',.) %>% dara.frame()
###查看數(shù)據(jù)
head(fin_res,3)
接下來添加分組變量及標(biāo)簽的x,y坐標(biāo):
###x坐標(biāo)
fin_res$x = c(rep(1.5,4),rep(2.5,4),rep(3.5,4),rep(4.5,4))
###y坐標(biāo)
fin_res$y= 0.65
#添加標(biāo)簽
fin_res$label = paste(fin_res$X2,"| n = ",fin_res$X1 , sep = '')
#添加變量
fin_res$Model = rep(names(table(fin_res$Model)),each = 4)
fin_res$variable = rep(c('PCC','PCC','SA','SA'),4)
fin_res$Dataset = rep(c('RPE1 DDA','RPE1 DIA'),8)
#查看數(shù)據(jù)
head(fin_res,3)
添加標(biāo)簽
p +
geom_text(data = fin_res,
aes(x = x , y = y,label = label),
##文本的角度及大小
angle = 90定庵, size = 4 )
生活很好吏饿,有你更好