Home > Net >  How do I merge two bar charts in matplotlib so the x axis is ordered?
How do I merge two bar charts in matplotlib so the x axis is ordered?

Time:01-11

I am trying to plot two data sets that have a string as x axis.

%matplotlib inline

at=['00', '10', '30', '40', '50', '60', '90']
a0=[2,3,4,5,6,7,8]
a1=[1,2,3,2,1,2,1]

bt=['20', '70', '80', '100']
b0=[4,5,6,7]
b1=[1,2,3,2]

plt.figure(figsize=(12,6))
plt.grid(visible=True, axis='y')
plt.bar(at, a1, bottom=a0, color='g', width=0.2)
plt.bar(bt, b1, bottom=b0, color='c', width=0.2)

This is the result of above code:

enter image description here

However, I would like the blue bars being inserted at the right positions, respecting the order. Given that those are strings, how could that be achieved?

CodePudding user response:

I suggest plotting the bars with actual horizontal numerical positions, and then afterwards setting the tick labels as you please. An example follows. Please note that I'm using the alternative Matplotlib API (I explicitly create figures and axes). This is immaterial here, and I'm sure you're able to adapt it to your style.

import matplotlib.pyplot as plt

at=[0, 10, 30, 40, 50, 60, 90]
a0=[2,3,4,5,6,7,8]
a1=[1,2,3,2,1,2,1]

bt=[20, 70, 80, 100]
b0=[4,5,6,7]
b1=[1,2,3,2]

fig = plt.figure(figsize=(12,6))
ax = fig.add_subplot(1,1,1)
ax.grid(visible=True, axis='y')
ax.bar(at, a1, bottom=a0, color='g', width=2, align="center") # I increased the width because yours were very narrow. I also centered the bars.
ax.bar(bt, b1, bottom=b0, color='c', width=2, align="center")

ticks = at   bt
ax.set_xticks(ticks)
ax.set_xticklabels(["{:02d}".format(t) for t in ticks]) # The format string here formats integers with two digits, padding with zeros.

plt.show()

The important things to note here is that at and bt now simply contain integers. Any formatting of what actually shows up as tick marks (such as 0 being displayed as "00") does not affect the overall placement of the bars.

The code above produces Output of suggested code

  •  Tags:  
  • Related