ggplot2:将p值添加到分组的箱形图中

时间:2018-08-12 09:05:04

标签: r ggplot2 grouping boxplot p-value

我正在尝试使用“ stat_signif”功能将p_values添加到图形中。
问题是我的箱线图是成组的箱形图,在这里我想比较相同类别的每2个箱形图,并且stat_signif函数需要x轴值进行比较。
这是我的代码:

p <- ggplot(plot.data, aes(x = Element, y = Value, fill = Group)) + #Define the elements for plotting - group by "strandness".
geom_boxplot(outlier.shape = NA, colour = "black") +
scale_fill_manual(values = c("goldenrod","darkgreen")) +
coord_cartesian(ylim = c(0, 0.03)) +
stat_summary(fun.y=mean, colour="black", geom ="point", shape=18, size=4 ,show.legend = FALSE, position = position_dodge(0.75)) +
theme(legend.title=element_blank(),legend.text = element_text(size=16), axis.text.x = element_text(color = "black", size = 12), axis.text.y = element_text(color = "black", size = 12),
      panel.background = element_blank(),
      panel.grid.major = element_blank(), 
      panel.grid.minor = element_blank(),
      axis.line = element_line(colour = "black"),
      panel.border = element_rect(colour = "black", fill=NA, size=0.5),
      legend.key = element_rect(colour = "transparent", fill = "white")) +
theme(plot.title = element_text(lineheight=.8, hjust = 0.5, size = 20),axis.title.y = element_text(size = 20, angle = 90, margin = margin(t = 0, r = 20, b = 0, l = 0))) +
labs(x = "", y = paste0(dinuc, " frequency")) +
theme(plot.margin = unit(c(2,1,1,1), "cm")) +
#stat_compare_means(aes(group = group))
stat_signif(comparisons = list(c("Genes", "mRNA"))
            ,test = "wilcox.test", test.args = list(paired = FALSE, exact = FALSE, correct = FALSE,
                                                    map_signif_level = T), y_position = 0.02) 

plot.data数据框的外观如下:

  Group, Value, Element
1 Transcribed, 0.004814926, Genes
2 Non-transcribed, 0.008926, Genes
3 Transcribed, 0.086000026, mRNA
4 Non-transcribed, 0.00548, mRNA
5 Transcribed, 0.258400078, Exons
6 Non-transcribed, 0.23008457, Exons
7 Transcribed, 0.00005687, Introns
8 Non-transcribed, 0.890000521, Introns

等(每个元素大约有10000行)

这是通过代码获得的数字: plot 当我实际上想比较每个元素的转录和非转录盒形图时。

1 个答案:

答案 0 :(得分:1)

您发布的数据不足以获取p值,因此我发布了一个示例,您可以根据自己的数据集进行调整:

library(tidyverse)
library(ggpubr)

mtcars %>%
  mutate_at(vars(am, cyl), as.factor) %>%
  ggplot(aes(cyl, disp, fill=am))+
  geom_boxplot()+
  stat_compare_means(aes(group = am))

enter image description here

如果只想在图中使用p值,则可以使用stat_compare_means(aes(group = am), label = "p.format")