BenT
BenT

Reputation: 3200

Matplotlib Bar Graph Overlapping of Bars

So I have created a bar graph but I am having trouble with overlapping bars. I thought that the problem was with the edges overlapping, but when I changed edges='none'the bars were just really slim.

I do believe my math is correct in assuming that 3 bars with a width of of .3 should be moving along the x axis by .3 and leaving a .1 gap between each set of bars. (Note x is increasing by 1)

I don't see why the bars end up overlapping and the overlap seems to get worse near the end of the graph.

ax = plt.subplot(111)
ax2 = ax.twinx()
ax.bar(x,EWtot,width=.3, color='b', align='center',label='Eyewall',edgecolor='b')
ax.bar(x + 0.3,ICtot,width=.3, color='g', align='center',label='Inner Core',edgecolor='g')
ax.bar(x + 0.6,RBtot,width=.3, color='r', align='center',label='RainBand',edgecolor='r')

Upvotes: 8

Views: 22446

Answers (1)

Rutger Kassies
Rutger Kassies

Reputation: 64493

I think its a combination of two factors. First you could increase the precision of your width and x-position a little by supplying some extra digits, or specifying them as a fraction.

Secondly the use of the edge (linewidth > 0) makes the bars overlap a little by default, the edge is centered, so half the edge is inside the bar, the other half outside. Disabling the edge entirely prevents any overlap.

Increasing the linewidth and setting an alpha might help you to identify whats going on exactly.

The example below illustrates this:

n = 10
x = np.arange(n)
a = np.random.rand(n)
b = np.random.rand(n)
c = np.random.rand(n)

fig, axs = plt.subplots(2,1,figsize=(10,8))

axs[0].bar(x, a, width=0.3, facecolor='b', edgecolor='b', linewidth=3, alpha=.5)
axs[0].bar(x+0.3, b, width=0.3, facecolor='r', edgecolor='r', linewidth=3, alpha=.5)
axs[0].bar(x+0.6, c, width=0.3, facecolor='g', edgecolor='g', linewidth=3, alpha=.5)

axs[1].bar(x, a, width=1/3, facecolor='b', alpha=.5, linewidth=0)
axs[1].bar(x+1/3, b, width=1/3, facecolor='r', alpha=.5, linewidth=0)
axs[1].bar(x+2/3, c, width=1/3, facecolor='g', alpha=.5, linewidth=0)

enter image description here

Upvotes: 12

Related Questions