简体   繁体   中英

Histogram bars cannot stacked using matplotlib in python

I have implemented a histogram plot using "matplotlib" in python. I have two variables x1 and x2 with 15 elements in each. when running the code, the histogram bars are not stacked instead they are overlapped, as shown in the figure below.

I want to plot a stacked histogram of the bars of the variables.

The is the code:

x1= [23, 25, 40, 35, 40, 53, 33, 28, 55, 34, 20, 37, 36, 23, 33]
x2= [36, 20, 27, 50, 34, 47, 18, 28, 52, 21, 44, 34, 13, 40, 49]
colors = ['blue', 'orange']
bins = [10,20,30,40,50,60]
fig, (ax0, ax1, ax2) = plt.subplots(nrows=3)

ax0.hist(x1,bins = bins,  histtype='bar',  label=colors[0], rwidth=0.8)
ax0.hist(x2,bins, histtype='bar', stacked=True, label=colors[1], rwidth=0.8)

ax1.hist(x1, bins = bins, histtype='bar',  label=colors[0], rwidth=0.8)
ax1.hist(x2,bins = bins, histtype='bar', stacked=True,  label=colors[1], rwidth=0.8)

ax2.hist(x1, bins = bins, histtype='bar',  label=colors[0], rwidth=0.8)
ax2.hist(x2,bins = bins, histtype='bar', stacked=True,  label=colors[1], rwidth=0.8)

plt.show()

Output 在此处输入图像描述

Try passing both the lists together and use stacked=True . Just passing a single list and using stacked=True doesn't make much sense.

ax0.hist([x1, x2], bins, histtype='bar', stacked=True, label=colors, rwidth=0.8)
ax1.hist([x1, x2], bins, histtype='bar', stacked=True, label=colors, rwidth=0.8)
ax2.hist([x1, x2], bins, histtype='bar', stacked=True, label=colors, rwidth=0.8)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM