【问题标题】:Is there a way to change the box plot color where data are significant in R有没有办法改变 R 中数据重要的箱线图颜色
【发布时间】:2020-06-27 00:03:51
【问题描述】:

我的数据如下:

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 不感兴趣

【问题讨论】:

    标签: r ggplot2 ggpubr


    【解决方案1】:
    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
    

    【讨论】:

    • @User20100,您尝试过 e.matt 提供的解决方案吗?如果它不起作用,也许您可​​以提供一个更好的可重现示例,其 t.test p 值低于 0.05。
    【解决方案2】:

    这可能不是最优雅的方法,但您可以在 ggplot2 之外计算 p 值,并使用 ifelse 语句,赋予您可以使用 scale_fill_identity 调用的颜色模式。

    这里是一个使用虚拟示例的示例:

    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()
    

    【讨论】:

    • 谢谢,但我对再次运行 t.test 不感兴趣,抱歉。它对我不起作用
    • 所以,首先澄清你的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 2019-01-16
    • 2017-07-05
    • 1970-01-01
    • 2020-12-10
    相关资源
    最近更新 更多