https://cran./web/packages/ggsignif/vignettes/intro.html 首先我們用示例數(shù)據(jù)跑一跑 > library(ggplot2) > library(ggsignif) > head(iris) Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 3 4.7 3.2 1.3 0.2 setosa 4 4.6 3.1 1.5 0.2 setosa 5 5.0 3.6 1.4 0.2 setosa 6 5.4 3.9 1.7 0.4 setosa > ggplot(iris, aes(x = Species, y = Sepal.Length)) + + geom_boxplot() + + geom_signif( + comparisons = list(c("versicolor", "virginica")) + )
效果圖如下 通過comparisons參數(shù)來手動指定需要比較的兩組,就會自動在上面添加p值和連線,默認都在頂部添加,當我么同時指定了多組數(shù)據(jù)的比較時,就會重疊,示例如下 > ggplot(iris, aes(x = Species, y = Sepal.Length)) + + geom_boxplot() + + geom_signif( + comparisons = list( + c("versicolor", "virginica"), + c("setosa", "virginica"), + c("setosa", "versicolor") + ) + )
效果圖如下
為了避免這個問題,ggsignif還支持直接指定文字注釋的內(nèi)容和橫線的寬高度,代碼如下 > ggplot(iris, aes(x = Species, y = Sepal.Length)) + + geom_boxplot() + + geom_signif( + annotations = c("First", "Second", "Third"), + y_position = c(8, 8.2, 8.5), + xmin = c(1, 2, 1), + xmax = c(2, 3, 3) + )
效果圖如下 掌握了基本用法之后,就可以來復現(xiàn)文章中的圖表了,首先是兩組間的差異,代碼如下 > data <- iris[iris$Species %in% c("versicolor", "virginica"), ] > ggplot(data, aes(x = Species, y = Sepal.Length, fill = Species)) + + geom_boxplot() + + geom_signif(comparisons = list(c("versicolor", "virginica"))) + + theme_classic() + + theme(legend.position = "top")
效果圖如下 再來復現(xiàn)一個三組比較的,文獻中插入如下所示 > ggplot(data, aes(x = Species, y = Sepal.Length, fill = Species)) + + geom_boxplot() + + geom_signif(comparisons = list(c("versicolor", "virginica"))) + + theme_classic() + + theme(legend.position = "top") > ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species)) + + geom_boxplot() + + geom_signif( + annotations = c("*", "**", "***"), + y_position = c(8, 8.2, 8.5), + xmin = c(1, 2, 1), + xmax = c(2, 3, 3) + ) + + theme_classic() + + theme(legend.position = "top")
效果圖如下 通過y_position, xmin, xmax參數(shù)來指定p值的位置,通過annotations參數(shù)指定標記的具體信息,提升了靈活性。
|