上次我們給大家介紹了用R的ggpubr包繪制各種散點圖,今天我們繼續(xù)學習ggpubr包繪制各種SCI發(fā)表級箱圖孤页。
library(ggpubr)
library(patchwork)#如果沒有安裝要先安裝
set.seed(123)#設種子數(shù)
首先生成一個隨機的數(shù)據集医增,該數(shù)據集有300個觀測,3個變量(分別是A,sex,smokestatus)
dataset=data.frame(A=c(rnorm(150,12,2), rnorm(150, 6,1)),
sex=sample(c("0","1"),300,replace=TRUE),
smokestatus=sample(c("1","2","3"),300,replace=TRUE))
繪制簡單箱圖:(下面的加號表示拼接圖形,如果不需要拼接裸扶,可以直接把加號去掉)
ggboxplot(dataset, x = "smokestatus", y = "A",
bxp.errorbar=T,#顯示誤差條
width = 0.5,#箱體的寬度
color = "smokestatus", #分組
palette="aaas",#使用雜志aaas的配色
)+
ggboxplot(dataset, x = "smokestatus", y = "A", width = 0.5, color = "smokestatus",
palette="aaas",bxp.errorbar=T,
orientation = "horizontal"#調整圖形方向為水平
)+
ggboxplot(dataset, x = "smokestatus", y = "A", width = 0.5,color = "smokestatus",
palette="aaas",bxp.errorbar=T,
notch = TRUE,#添加缺口
order = c("3","2","1")#調整順序
)+
ggboxplot(dataset, x = "smokestatus", y = "A", width = 0.5, color = "smokestatus",
palette="aaas",bxp.errorbar=T,
select = c("3")#選擇特定的水平來畫圖 )
繪制帶散點的箱圖
ggboxplot(dataset, x = "smokestatus", y = "A", width = 0.8,
add = "jitter",#添加圖形元素
add.params=list(color = "smokestatus",size=0.8, shape = 23))#參數(shù)add的參數(shù),可設置顏色
繪制簇狀箱圖(橫坐標表示smokestatus分組搬素,不同顏色代表不同性別sex)
ggboxplot(dataset, x = "smokestatus", y = "A", width = 0.6,
color = "black",#輪廓顏色
fill="sex",#填充
palette =c("#E7B800", "#00AFBB"),#分組著色
xlab = F, #不顯示x軸的標簽
bxp.errorbar=T,#顯示誤差條
bxp.errorbar.width=0.5, #誤差條大小
size=1, #箱型圖邊線的粗細
outlier.shape=NA, #不顯示outlier
legend = "right") #圖例放右邊
在箱圖添加三組總體P值
ggboxplot(dataset, x = "smokestatus", y = "A", width = 0.8,
add = "jitter",add.params=list(color = "smokestatus",size=0.5))+
stat_compare_means(method = "anova")
兩兩比較
my_comparisons <- list( c("1", "2"), c("1", "3"), c("3", "2") )
ggboxplot(dataset, x = "smokestatus", y = "A",
color = "smokestatus", palette = "npg")+
#兩兩比較的p值
stat_compare_means(comparisons = my_comparisons, label.y = c(18, 22, 26))+
#整體的p值
stat_compare_means(label.y = 28)
固定某一組呵晨,其他與某組比較
ggboxplot(dataset, x = "smokestatus", y = "A",
color = "smokestatus", palette = "npg")+
# 整體的p值
stat_compare_means(method = "anova", label.y = 28)+
stat_compare_means(method = "t.test", #選擇統(tǒng)計方法
ref.group = "1"#以smokestatus為1的作為對照組
)
分組/分面之后再做比較
ggboxplot(dataset, x = "sex", y = "A",
color = "sex", palette = "npg",
add = "jitter",
facet.by = "smokestatus"#按照smokestatus分不同的面板
)+
#label中去掉檢驗方法
stat_compare_means(aes(label = paste0("p = ", ..p.format..)))
今天箱圖的學習到這。
歡迎大家關注?R語言與SPSS學習筆記 公眾號