ggplot2:如何在密度图中添加显着性条?

时间:2017-05-03 08:30:22

标签: r ggplot2

我正在尝试使用显着性检验生成(分组)密度图 我用箱形图(包含ggsignif包)做到了,但我不知道如何在densityplot中做什么

setwd("~/myData")

data<-read.delim("genes.txt", head=T, row.names = 1)
data$Variance<-apply(data, 1, var)

head(data)
dim(data)

library(ggplot2)

library(ggsignif)

ggplot(data, aes(x=variance, col=type)) +geom_density() )
 geom_signif(comparisons = list(c("normal", "traited")),map_signif_level=TRUE)

我有这个错误:

error in f(...)
can oly handle data with groupes that are plotted on the x-axis 

enter image description here

1 个答案:

答案 0 :(得分:0)

正如评论中所写,我猜在ggsignif中还没有实现bar的类型。这里有一个手动解决方法,包括一些手动预处理(均值,pvalue)和后处理(通过调整垂直位置使其看起来很漂亮)。

x = rnorm(10000,2)
y = rnorm(10000,-1)

require(ggplot2)

df1=data.frame(val=x,type="x")
df2=data.frame(val=y,type="y")
df.complete = rbind(df1,df2)

mean1 = mean(x)
mean2 = mean(y)
middle = (mean1 + mean2)/2

pval = 0.001 #replace by appropriate p-value from test of choice

g = ggplot(df.complete,aes(x=val,fill=type))
g = g + geom_density()
g = g + ylim(0,0.5) #enlarge sufficiently to have some space
g = g + geom_segment(aes(x=mean1,y=0.425,xend=mean1,yend=0.45)) #correct y and yend after visual inspection
g = g + geom_segment(aes(x=mean2,y=0.425,xend=mean2,yend=0.45)) #correct y and yend after visual inspection
g = g + geom_segment(aes(x=mean2,y=0.45,xend=mean1,yend=0.45))  #correct y and yend after visual inspection
g = g + geom_text(aes(x=middle,y=0.47,label=pval),hjust="center") #correct y after visual inspection
g

http://www.r-fiddle.org/#/fiddle?id=NUxpKHlv&version=2

相关问题