原文见https://github.com/const-ae/ggsignif
不同的组的数据图,各种统计分析后有显著差异的结果,经常要添加显著性标注,ggplot2可以画标注线,但是比较繁琐。用ggsignif包可以完美的解决这个问题。
安装包
install.packages("ggsignif")
# Or for the latest development version
devtools::install_github("const-ae/ggsignif")
绘制显著性标注
library(ggplot2)
library(ggsignif)
ggplot(mpg, aes(class, hwy)) +
geom_boxplot() +
geom_signif(comparisons = list(c("compact", "midsize"), c("minivan", "suv")),
map_signif_level = TRUE, textsize=6) +
ylim(NA, 48)

image.png
设置标注的精确位置
# Calculate annotation
anno <- t.test(iris[iris$Petal.Width > 1 & iris$Species == "versicolor", "Sepal.Width"],
iris[iris$Species == "virginica", "Sepal.Width"])$p.value
# Make plot with custom x and y position of the bracket
ggplot(iris, aes(x=Species, y=Sepal.Width, fill=Petal.Width > 1)) +
geom_boxplot(position="dodge") +
geom_signif(annotation=formatC(anno, digits=1),
y_position=4.05, xmin=2.2, xmax=3,
tip_length = c(0.2, 0.04))

image.png
高级绘图
annotation_df <- data.frame(color=c("E", "H"),
start=c("Good", "Fair"),
end=c("Very Good", "Good"),
y=c(3.6, 4.7),
label=c("Comp. 1", "Comp. 2"))
annotation_df
#> color start end y label
#> 1 E Good Very Good 3.6 Comp. 1
#> 2 H Fair Good 4.7 Comp. 2
ggplot(diamonds, aes(x=cut, y=carat)) +
geom_boxplot() +
geom_signif(data=annotation_df,
aes(xmin=start, xmax=end, annotations=label, y_position=y),
textsize = 3, vjust = -0.2,
manual=TRUE) +
facet_wrap(~ color) +
ylim(NA, 5.3)

image.png
更多的例子
ggplot(iris, aes(x=Species, y=Sepal.Length)) +
geom_boxplot() +
geom_signif(comparisons = list(c("versicolor", "virginica")),
map_signif_level=TRUE)

image.png
dat <- data.frame(Group = c("S1", "S1", "S2", "S2"),
Sub = c("A", "B", "A", "B"),
Value = c(3,5,7,8))
ggplot(dat, aes(Group, Value)) +
geom_bar(aes(fill = Sub), stat="identity", position="dodge", width=.5) +
geom_signif(y_position=c(5.3, 8.3), xmin=c(0.8, 1.8), xmax=c(1.2, 2.2),
annotation=c("**", "NS"), tip_length=0) +
geom_signif(comparisons=list(c("S1", "S2")),
y_position = 9.3, tip_length = 0, vjust=0.2) +
scale_fill_manual(values = c("grey80", "grey20"))

image.png
网友评论