【问题标题】:ggplot2 boxplots - How to avoid extra vertical space when there are no significant comparisons?ggplot2 boxplots - 当没有显着比较时如何避免额外的垂直空间?
【发布时间】:2017-10-05 07:52:58
【问题描述】:

在许多关于如何制作带有分面和显着性水平的箱线图的问题之后,尤其是thisthis,我还有一个小问题。

我设法制作了如下所示的情节,这正是我想要的。

我现在面临的问题是当我很少或没有重要的比较时;在这些情况下,用于显示显着性级别的括号的整个空间仍然保留,但我想摆脱它。

请使用 iris 数据集检查此 MWE:

library(reshape2)
library(ggplot2)
data(iris)
iris$treatment <- rep(c("A","B"), length(iris$Species)/2)
mydf <- melt(iris, measure.vars=names(iris)[1:4])
mydf$treatment <- as.factor(mydf$treatment)
mydf$variable <- factor(mydf$variable, levels=sort(levels(mydf$variable)))
mydf$both <- factor(paste(mydf$treatment, mydf$variable), levels=(unique(paste(mydf$treatment, mydf$variable))))
a <- combn(levels(mydf$both), 2, simplify = FALSE)#this 6 times, for each lipid class
b <- levels(mydf$Species)
CNb <- relist(
    paste(unlist(a), rep(b, each=sum(lengths(a)))), 
    rep.int(a, length(b))
)
CNb
CNb2 <- data.frame(matrix(unlist(CNb), ncol=2, byrow=T))
CNb2
#new p.values
pv.df <- data.frame()
for (gr in unique(mydf$Species)){
    for (i in 1:length(a)){
        tis <- a[[i]] #variable pair to test
        as <- subset(mydf, Species==gr & both %in% tis)
        pv <- wilcox.test(value ~ both, data=as)$p.value
        ddd <- data.table(as)
        asm <- as.data.frame(ddd[, list(value=mean(value)), by=list(both=both)])
        asm2 <- dcast(asm, .~both, value.var="value")[,-1]
        pf <- data.frame(group1=paste(tis[1], gr), group2=paste(tis[2], gr), mean.group1=asm2[,1], mean.group2=asm2[,2], log.FC.1over2=log2(asm2[,1]/asm2[,2]), p.value=pv)
        pv.df <- rbind(pv.df, pf)
    }
}
pv.df$p.adjust <- p.adjust(pv.df$p.value, method="BH")
colnames(CNb2) <- colnames(pv.df)[1:2]
# merge with the CN list
pv.final <- merge(CNb2, pv.df, by.x = c("group1", "group2"), by.y = c("group1", "group2"))
# fix ordering
pv.final <- pv.final[match(paste(CNb2$group1, CNb2$group2), paste(pv.final$group1, pv.final$group2)),]
# set signif level
pv.final$map.signif <- ifelse(pv.final$p.adjust > 0.05, "", ifelse(pv.final$p.adjust > 0.01,"*", "**"))
# subset
G <- pv.final$p.adjust <= 0.05
CNb[G]
P <- ggplot(mydf,aes(x=both, y=value)) +
    geom_boxplot(aes(fill=Species)) +
    facet_grid(~Species, scales="free", space="free_x") +
    theme(axis.text.x = element_text(angle=45, hjust=1)) +
    geom_signif(test="wilcox.test", comparisons = combn(levels(mydf$both),2, simplify = F),
              map_signif_level = F,            
              vjust=0.5,
              textsize=4,
              size=0.5,
              step_increase = 0.06)
P2 <- ggplot_build(P)

#pv.final$map.signif <- "" #UNCOMMENT THIS LINE TO MOCK A CASE WHERE THERE ARE NO SIGNIFICANT COMPARISONS
#pv.final$map.signif[c(1:42,44:80,82:84)] <- "" #UNCOMMENT THIS LINE TO MOCK A CASE WHERE THERE ARE JUST A COUPLE OF SIGNIFICANT COMPARISONS

P2$data[[2]]$annotation <- rep(pv.final$map.signif, each=3)
# remove non significants
P2$data[[2]] <- P2$data[[2]][P2$data[[2]]$annotation != "",]
# and the final plot
png(filename="test.png", height=800, width=800)
  plot(ggplot_gtable(P2))
dev.off()

这会产生这个情节:

上面的情节正是我想要的......但我面临的情况是没有重要的比较,或者很少。在这些情况下,很多垂直空间都是空的。

为了举例说明这些场景,我们可以取消注释该行:

pv.final$map.signif <- "" #UNCOMMENT THIS LINE TO MOCK A CASE WHERE THERE ARE NO SIGNIFICANT COMPARISONS

所以当没有重要的比较时,我会得到这个情节:

如果我们取消注释另一行:

pv.final$map.signif[c(1:42,44:80,82:84)] <- "" #UNCOMMENT THIS LINE TO MOCK A CASE WHERE THERE ARE JUST A COUPLE OF SIGNIFICANT COMPARISONS

我们在一个只有几个显着比较的情况下,得到这个图:

所以我的问题是:

如何将垂直空间调整为显着比较的个数,这样就没有垂直空间了?

step_increasegeom_signif() 内的y_position 中可能有一些东西我可以更改,所以我只为CNb[G] 中的重要比较留出空间...

【问题讨论】:

  • 看来您引用的第一个链接中的最后一个示例确实/显示了您想要的内容,所以为什么不将您的示例简化为类似的内容,看看您是否可以重现该数字然后建立备份到您的完整数据?
  • 事实并非如此......在那个链接中,答案不会隐藏不重要的比较,这就是为什么我需要在情节之外进行测试然后更改情节的注释(如@ 987654326@)
  • 但是你正在做一些事情......就像我提供的第一个链接一样,我可能可以在geom_signif() 内做comparisons=CNb[G]......这只会为重要的比较留出空间...让我试着回复你
  • @DaniCee 没用,我试过了 :(
  • 到目前为止我没有尝试过任何工作......你们中的任何人都有线索吗?谢谢!

标签: r ggplot2


【解决方案1】:

一种选择是预先计算both 水平的每个组合的 p 值,然后仅选择显着的水平进行绘图。由于我们预先知道有多少是重要的,我们可以调整图的 y 范围来解释这一点。但是,geom_signif 似乎不能仅对 p 值注释进行内部计算(请参阅manual 参数的帮助)。因此,我们不使用 ggplot 的分面,而是使用lapply 为每个Species 创建一个单独的图,然后使用gridExtra 包中的grid.arrange 来布置各个图,就好像它们是分面的一样。

(为了回应 cmets,我想强调的是,这些图仍然是使用 ggplot2 创建的,但我们将单个图的三个面面板创建为 三个单独的图然后将它们放在一起,就好像它们被刻面一样。)

下面的函数是针对 OP 中的数据框和列名称进行硬编码的,但当然可以泛化为采用任何数据框和列名称。

library(gridExtra)
library(tidyverse)

# Change data to reduce number of statistically significant differences
set.seed(2)
df = mydf %>% mutate(value=rnorm(nrow(mydf)))

# Function to generate and lay out the plots
signif_plot = function(signif.cutoff=0.05, height.factor=0.23) {

  # Get full range of y-values
  y_rng = range(df$value)

  # Generate a list of three plots, one for each Species (these are the facets)
  plot_list = lapply(split(df, df$Species), function(d) {

    # Get pairs of x-values for current facet
    pairs = combn(sort(as.character(unique(d$both))), 2, simplify=FALSE)

    # Run wilcox test on every pair
    w.tst =  pairs %>% 
      map_df(function(lv) { 
        p.value = wilcox.test(d$value[d$both==lv[1]], d$value[d$both==lv[2]])$p.value
        data.frame(levs=paste(lv, collapse=" "), p.value)
      })

    # Record number of significant p.values. We'll use this later to adjust the top of the
    # y-range of the plots
    num_signif = sum(w.tst$p.value <= signif.cutoff)

    # Plot significance levels only for combinations with p <= signif.cutoff
    p = ggplot(d, aes(x=both, y=value)) +
      geom_boxplot() +
      facet_grid(~Species, scales="free", space="free_x") +
      geom_signif(test="wilcox.test", comparisons = pairs[which(w.tst$p.value <= signif.cutoff)],
                  map_signif_level = F,            
                  vjust=0,
                  textsize=3,
                  size=0.5,
                  step_increase = 0.08) +
      theme_bw() +
      theme(axis.title=element_blank(),
            axis.text.x = element_text(angle=45, hjust=1))

    # Return the plot and the number of significant p-values
    return(list(num_signif, p))
  })

  # Get the highest number of significant p-values across all three "facets"
  max_signif = max(sapply(plot_list, function(x) x[[1]]))

  # Lay out the three plots as facets (one for each Species), but adjust so that y-range is same
  # for each facet. Top of y-range is adjusted using max_signif.
  grid.arrange(grobs=lapply(plot_list, function(x) x[[2]] + 
                              scale_y_continuous(limits=c(y_rng[1], y_rng[2] + height.factor*max_signif))), 
               ncol=3, left="Value")
}

现在运行具有四个不同重要性截止值的函数:

signif_plot(0.05)

signif_plot(0.01)

signif_plot(0.9)

signif_plot(0.0015)

【讨论】:

  • 有没有办法把这个保存在ggplot2中?
  • 您的意思是要避免使用 ggplot2 代码以外的任何代码?我认为这将需要对geom_signif 进行增强以本地处理构面(通过按构面生成显着性注释,而不是向所有构面添加相同的注释)并允许不为非显着性测试绘制注释。
  • 如果可能的话,为了保持一致性,我宁愿坚持使用 ggplot2,因为我所有的情节都是这样完成的......
  • 我的答案中的绘图全部在 ggplot2 中,但有些计算必须在对 ggplot2 的实际调用之外完成。
  • 关于Error in map_df...:我忘记在我的代码中包含purrr 包。我已经通过添加library(tidyverse) 来解决这个问题,它加载了ggplot2purrr,以及其他几个属于tidyverse 的相关包。
【解决方案2】:

你可以试试。虽然答案和我的答案here类似,但我现在加了一个函数。

library(tidyverse)
library(ggsignif)
# 1. your data
set.seed(2)
df <- as.tbl(iris) %>% 
  mutate(treatment=rep(c("A","B"), length(iris$Species)/2)) %>% 
  gather(key, value, -Species, -treatment) %>% 
  mutate(value=rnorm(n())) %>% 
  mutate(key=factor(key, levels=unique(key))) %>% 
  mutate(both=interaction(treatment, key, sep = " "))

# 2. pairwise.wilcox.test for 1) validation and 2) to calculate the ylim
Wilcox <- df %>% 
  split(., .$Species) %>% 
  map(~tidy(pairwise.wilcox.test(.$value, .$both, p.adjust.method =  "none"))) %>% 
  map(~filter(.,.$p.value < 0.05)) %>% 
  bind_rows(.id="Species") %>% 
  mutate(padjust=p.adjust(p.value, method = "BH"))

# 3. calculate y range
Ylim <- df %>% 
  summarise(Min=round(min(value)),
            Max=round(max(value))) %>% 
  mutate(Max=Max+0.5*group_by(Wilcox, Species) %>% count() %>% with(.,max(n))) 
  %>% c()

# 4. the plot function 
foo <- function(df, Ylim, Signif=0.05){
P <- df %>% 
ggplot(aes(x=both, y=value)) + 
  geom_boxplot(aes(fill=Species)) + 
  facet_grid(~Species) +
  ylim(Ylim$Min, Ylim$Max)+
  theme(axis.text.x = element_text(angle=45, hjust=1)) +
  geom_signif(comparisons = combn(levels(df$both),2,simplify = F),
              map_signif_level = F, test = "wilcox.test" ) +
  stat_summary(fun.y=mean, geom="point", shape=5, size=4) +
  xlab("") 
# 5. remove not significant values and add step increase
P_new <- ggplot_build(P)
P_new$data[[2]] <- P_new$data[[2]] %>% 
  filter(as.numeric(as.character(annotation)) < 0.05) %>% 
  group_by(PANEL) %>%
  mutate(index=(as.numeric(group[drop=T])-1)*0.5) %>% 
  mutate(y=y+index,
         yend=yend+index) %>% 
  select(-index) %>% 
  as.data.frame()
# the final plot  
plot(ggplot_gtable(P_new))
}

foo(df, Ylim)

尝试其他数据

set.seed(12345)
df <- as.tbl(iris) %>% 
  mutate(treatment=rep(c("A","B"), length(iris$Species)/2)) %>% 
  gather(key, value, -Species, -treatment) %>% 
  mutate(value=rnorm(n())) %>% 
  mutate(key=factor(key, levels=unique(key))) %>% 
  mutate(both=interaction(treatment, key, sep = " "))

foo(df, list(Min=-3,Max=5))

当然,您也可以将 Ylim 计算添加到函数中。此外,您可以更改或添加ggtitel()ylab() 并更改颜色。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    相关资源
    最近更新 更多