title: Grouped barplot in R with error bars
body: <p>I would like to draw a grouped barplot with error bars. Here is the kind of figure I have been able to get up to now, and this is ok for what I need:</p>
  
  <p><img src="https://i.stack.imgur.com/UcQCI.png" alt="enter image description here"></p>
  
  <p>And here is my script:</p>
  
  <pre><code>#create dataframe
  Gene&lt;-c("Gene1","Gene2","Gene1","Gene2")
  count1&lt;-c(12,14,16,34)
  count2&lt;-c(4,7,9,23)
  count3&lt;-c(36,22,54,12)
  count4&lt;-c(12,24,35,23)
  Species&lt;-c("A","A","B","B")
  df&lt;-data.frame(Gene,count1,count2,count3,count4,Species)
  df
  
  mean1&lt;-mean(as.numeric(df[1,][c(2,3,4,5)]))
  mean2&lt;-mean(as.numeric(df[2,][c(2,3,4,5)]))
  mean3&lt;-mean(as.numeric(df[3,][c(2,3,4,5)]))
  mean4&lt;-mean(as.numeric(df[4,][c(2,3,4,5)]))
  Gene1SpeciesA.stdev&lt;-sd(as.numeric(df[1,][c(2,3,4,5)]))
  Gene2SpeciesA.stdev&lt;-sd(as.numeric(df[2,][c(2,3,4,5)]))
  Gene1SpeciesB.stdev&lt;-sd(as.numeric(df[3,][c(2,3,4,5)]))
  Gene2SpeciesB.stdev&lt;-sd(as.numeric(df[4,][c(2,3,4,5)]))
  
  ToPlot&lt;-c(mean1,mean2,mean3,mean4)
  
  #plot barplot
  plot&lt;-matrix(ToPlot,2,2,byrow=TRUE)   #with 2 being replaced by the number of genes!
  tplot&lt;-t(plot)
  BarPlot &lt;- barplot(tplot, beside=TRUE,ylab="count",
                  names.arg=c("Gene1","Gene2"),col=c("blue","red"))
  
  #add legend
  legend("topright", 
         legend = c("SpeciesA","SpeciesB"), 
         fill = c("blue","red"))
  
  #add error bars
  ee&lt;-matrix(c(Gene1SpeciesA.stdev,Gene2SpeciesA.stdev,Gene1SpeciesB.stdev,Gene2SpeciesB.stdev),2,2,byrow=TRUE)*1.96/sqrt(4)   
  tee&lt;-t(ee)
  error.bar(BarPlot,tplot,tee)
  </code></pre>
  
  <p>The problem is that I need to do this for 50 genes, and 4 species, so my script is gonna get super super long and I guess this is not optimized... I tried to find help <a href="http://www.cookbook-r.com/Graphs/Plotting_means_and_error_bars_(ggplot2)/" rel="noreferrer">here</a> but I can't figure out a better way to do what I'd like. If I did not need error bars I could adapt <a href="https://stackoverflow.com/questions/18158461/grouped-bar-plot-in-ggplot">this script</a> but the tricky part is to mix ggplot beautiful barplots and error bars! ;)</p>
  
  <p>If you have any idea to optimize my script, I would really appreciate! :)</p>
  
  <p>Thanks a lot!</p>