[英]Is there a way to change the box plot color where data are significant in R
My data are as follows:我的数据如下:
df1<-read.table(text = "time type 12 B88 19 B44 18 B44 13 B88 17 B44",header=TRUE)
I can use the following codes to get my plot:我可以使用以下代码来获取我的情节:
ggplot(df1,aes(type,time)) + geom_boxplot(fill="green")+ stat_compare_means(method = "t.test")
I want to get a different colour, let's say blue, for the box which has a high medium when the P-value is less than 0.05%.当 P 值小于 0.05% 时,我想为具有高中值的盒子获得不同的颜色,比如说蓝色。 Can we do it?我们能做到吗? NOTE: I am not interested in running ttest注意:我对运行 ttest 不感兴趣
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
Probably not the most elegant way of doing it but you can calculate the p value outside ggplot2
and using an ifelse
statement, attribute a color pattern you can call using scale_fill_identity
.可能不是最优雅的方法,但您可以在ggplot2
之外计算 p 值并使用ifelse
语句,属性您可以使用scale_fill_identity
调用的颜色模式。
Here an example using a dummy example:这是一个使用虚拟示例的示例:
df <- data.frame(Xval = rep(c("A","B"),each = 50),
Yval = c(sample(1:50,50), sample(50:100,50)))
I used dplyr
pipe sequence here but you cna do that pretty easily in base r
:我在这里使用了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()
Using your example:使用您的示例:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.