rfor-loopggplot2annotationsp-value

How to manually add multiple geom_signif() to a cluster bar graph with a for loop?


I am creating a cluster bar graph and want to add significant astricks according to when a significance occurs from previously calcualted statistics. As there is the potential for multiple astricks to be annotated between certain columns, i want to for loop the ggplot() with geom_sign().

df <- data.frame(
  mouse = rep(1:5, each = 4),
  treatment = rep(rep(c("A", "B"), each = 2), times = 5),
  poke_type = rep(rep(c("Left", "Right"), times = 2), times = 5),
  pokes = rpois(20, lambda = 5)
)

#means
mean_df%>%
 group_by(treatment, poke_type)%>%
 summarize(mean=mean(pokes))

#complete pairwise comparison and produce dataframe with astricks for annotations

annotations_df <- data.frame(
 main=c("A","B","Left","Right"),
 group1=c("Left","Right","A","B"),
 group2=c("Right","Left","B","A"),
 pval_symbol=c("*","n.s","**","n.s"),
 xmin_index=c(0.8,2.8,0.8,2.8),
 xmax_index=c(1.2,3.2,2.8,3.2),
 y=c(210,210,210,210))

#cluster bar graph
plot<-mean_df%>%
 ggplot(aes(x=treatment,y=mean, fill=poke_type)+
 geom_bar(stat='identity',position='dodge',color= 'black',size=0.7)

#add significance on cluster bar graph according to annotation_df

my attempt so far:

  if(any(annotations_df$pval_symbol!="n.s")){
    row_index<<-which(annotations_df$pval_symbol != "n.s")
    for(i in row_index){
      index <- as.numeric(i)
      plot<- plot+geom_signif(
        data = annotations_df,
        aes(xmin=annotations_df$xmin_index[index],
            xmax=annotations_df$xmax_index[index],
            annotations=annotations_df$pval_symbol[index],
            y_position=annotations_df$y[index]),
        textsize=10,size=0.8,manual=TRUE,inherit.aes = FALSE, tip_length = 0.1)}
  } else {}

Solution

  • No need to for loop

    if(any(annotations_df$pval_symbol!="n.s")){
        index_df<-annotations_df[annotations_df$pval_symbol != "n.s",]
    
        plot<- plot+geom_signif(
          data = index_df,
          aes(xmin=index_df$xmin_index,
              xmax=index_df$xmax_index,
              annotations=index_df$pval_symbol,
              y_position=index_df$y),
          textsize=10,size=0.8,manual=TRUE,inherit.aes = FALSE)
    
    } else {}