ggplot(df1,aes(type,time)) + geom_boxplot(fill="green") +
stat_compare_means(method = "t.test") -> p #save your plot as p
build <- ggplot_build(p) # build plot
build$data[[1]][,"fill"] <- ifelse(build$data[[2]][1,"p.format"] < 0.05,list(c("blue","green")),list(rep("green",2))) # changes fill to blue if p value is < 0.05
plot(ggplot_gtable(build)) # plot new formatted graph
,
可能不是最优雅的方式,但是您可以在ggplot2
外部并使用ifelse
语句来计算p值,并为可以使用scale_fill_identity
调用的颜色模式赋予属性。 / p>
下面是一个使用虚拟示例的示例:
df <- data.frame(Xval = rep(c("A","B"),each = 50),Yval = c(sample(1:50,50),sample(50:100,50)))
我在这里使用了dplyr
管道序列,但是您可以在base r
中很容易地做到这一点:
library(dplyr)
library(ggplot2)
df %>% mutate(pval = t.test(Yval~Xval)$p.value) %>%
group_by(Xval) %>% mutate(Mean = mean(Yval)) %>%
ungroup() %>%
mutate(Color = ifelse(pval < 0.05 & Mean == max(Mean),"blue","green")) %>%
ggplot(aes(x = Xval,y = Yval,fill = Color))+
geom_boxplot()+
stat_compare_means(method = "t.test")+
scale_fill_identity()
使用您的示例:
df1 %>% mutate(pval = t.test(time~type)$p.value) %>%
group_by(type) %>% mutate(Mean = mean(time)) %>%
ungroup() %>%
mutate(Color = ifelse(pval < 0.05 & Mean == max(Mean),"green")) %>%
ggplot(aes(x = type,y = time,fill = Color))+
geom_boxplot()+
stat_compare_means(method = "t.test")+
scale_fill_identity()
本文链接:https://www.f2er.com/2642320.html