title: Aligning error bars with different numbers of bars per group in ggplot2
body: <p>I was trying to plot error bars on a bar plot in ggplot2 with different number of bars per group. I would like:</p>
  
  <ul>
  <li>Fixed width of bars, regardless of number of bars per group</li>
  <li>Error bars with the same width of whiskers, aligned with the corresponding bars</li>
  </ul>
  
  <p>This should be pretty standard, but I am struggling with the error bars, as the settings in <code>position_dodge()</code> and <code>position_dodge2()</code> did not seem to be as straight-forward as the examples in the <code>geom_crossbar()</code> and the <code>position_dodge</code> documentation.</p>
  
  <p>My closest attempt is:</p>
  
  <pre><code>df &lt;- data.frame(
    mean = 2:8,
    loc = c(rep(1, 4), 2, rep(3, 2)),
    # spcs = c(1:4, 1, 1:2),
    spcs = c(1:4, 1, 2, 4)  # Updated on 29 Dec 2018 in response to @Roman Luštrik's comment
  )
  ggplot(aes(x = factor(loc), y = mean, fill = factor(spcs)), data = df) + 
    geom_col(position = position_dodge2(preserve = "single")) +
    geom_errorbar(
      aes(ymin = mean - 0.2, ymax = mean + 0.2),
      position = position_dodge(width = 0.9),
      width = 0.2
    )
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/Udos2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Udos2.png" alt="enter image description here"></a></p>
  
  <p>However, neither the error bars were aligned with the bars (Loc 3), nor did they have the same width of whiskers as I wished (Locs 2 and 3).</p>
  
  <p>I have googled and found a few similar questions here, but not exactly my case. I would therefore appreciate a solution with a bit explanation on why my attempt failed.</p>
  
  <p>ps. I know if I <code>facet_grid()</code> by <code>loc</code> and set <code>scales = "free_x", space = "free_x"</code> I would get a close alternative, but I would rather not use facet here. Thanks!</p>