我的数据如下:
df1<-read.table(text = "time type
12 B88
19 B44
18 B44
13 B88
17 B44",header=TRUE)
我可以使用以下代码获取我的情节:
ggplot(df1,aes(type,time)) + geom_boxplot(fill="green")+
stat_compare_means(method = "t.test")
对于P值小于0.05%时具有中等中等含量的盒子,我想使用不同的颜色,例如蓝色。我们可以做到吗? 注意:我对运行ttest不感兴趣
答案 0 :(得分:3)
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
答案 1 :(得分:1)
可能不是最优雅的方式,但是您可以在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), "blue","green")) %>%
ggplot(aes(x = type, y = time, fill = Color))+
geom_boxplot()+
stat_compare_means(method = "t.test")+
scale_fill_identity()