title: Stacked Bar Chart with Centered Labels
body: <p>I'm trying to &quot;robustly&quot; center the data labels in a stacked bar chart. A simple code example and the result are given below. As you can see, the data labels aren't really centered in all rectangles. What am I missing?</p>
  <pre><code>import numpy as np
  import matplotlib.pyplot as plt
  
  A = [45, 17, 47]
  B = [91, 70, 72]
  
  fig = plt.figure(facecolor=&quot;white&quot;)
  
  ax = fig.add_subplot(1, 1, 1)
  bar_width = 0.5
  bar_l = np.arange(1, 4)
  tick_pos = [i + (bar_width / 2) for i in bar_l]
  
  ax1 = ax.bar(bar_l, A, width=bar_width, label=&quot;A&quot;, color=&quot;green&quot;)
  ax2 = ax.bar(bar_l, B, bottom=A, width=bar_width, label=&quot;B&quot;, color=&quot;blue&quot;)
  ax.set_ylabel(&quot;Count&quot;, fontsize=18)
  ax.set_xlabel(&quot;Class&quot;, fontsize=18)
  ax.legend(loc=&quot;best&quot;)
  plt.xticks(tick_pos, [&quot;C1&quot;, &quot;C2&quot;, &quot;C3&quot;], fontsize=16)
  plt.yticks(fontsize=16)
  
  for r1, r2 in zip(ax1, ax2):
      h1 = r1.get_height()
      h2 = r2.get_height()
      plt.text(r1.get_x() + r1.get_width() / 2., h1 / 2., &quot;%d&quot; % h1, ha=&quot;center&quot;, va=&quot;bottom&quot;, color=&quot;white&quot;, fontsize=16, fontweight=&quot;bold&quot;)
      plt.text(r2.get_x() + r2.get_width() / 2., h1 + h2 / 2., &quot;%d&quot; % h2, ha=&quot;center&quot;, va=&quot;bottom&quot;, color=&quot;white&quot;, fontsize=16, fontweight=&quot;bold&quot;)
  
  plt.show()
  </code></pre>
  <p><a href="https://i.stack.imgur.com/E25Bl.png" rel="noreferrer"><img src="https://i.stack.imgur.com/E25Bl.png" alt="" /></a></p>