![](/img/trans.png)
[英]How to draw two stacked histograms side-by-side with Matplotlib/Seaborn
[英]How do I plot stacked histograms side by side in matplotlib?
我想在matplotlib中繪制兩個並排堆疊的直方圖(類似於下面的示例圖像)。 我嘗試了幾種變體
bins = np.arange(10)
a1,b1,c1 =plt.hist([arr1,arr2,arr3],bins,stacked=True)
a2,b2,c2 =plt.hist([arr4,arr5,arr6],bins,stacked=True)
但似乎無法避免讓第二個情節直接覆蓋第一個。 關於如何解決這個問題的任何想法?
圖為條形圖而非直方圖 。 我指出這一點,不僅因為我是一個討厭的學究,而且因為我相信它可以幫助你找到合適的工具:-)
事實上,為了你的目的, plt.bar
可能是比plt.hist
更好的選擇。
根據Scironic的建議,我修改了這個演示示例來制作堆疊條,就像你圖中的那些。
向位置索引添加偏移量( plt.bar()
第一個參數)可以防止條形圖相互重疊。
import numpy as np
import matplotlib.pyplot as plt
N = 5
men1 = (130, 90, 70, 64, 55)
men2 = (120, 85, 62, 50, 53)
men3 = (100, 70, 60, 45, 50)
ind = np.arange(N) + .15 # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind, men1, width, color='g')
rects2 = ax.bar(ind, men2, width, color='r')
rects3 = ax.bar(ind, men3, width, color='b')
women4 = (140, 90, 78, 65, 50)
women5 = (130, 80, 70, 60, 45)
women6 = (120, 60, 60, 55, 44)
xtra_space = 0.05
rects2 = ax.bar(ind + width + xtra_space , women1, width, color='orange')
rects2 = ax.bar(ind + width + xtra_space, women2, width, color='cyan')
rects2 = ax.bar(ind + width + xtra_space, women3, width, color='purple')
# add some text for labels, title and axes ticks
ax.set_ylabel('Population, millions')
ax.set_title('Population: Age Structure')
ax.set_xticks(ind+width+xtra_space)
ax.set_xticklabels( ('USA', 'Brazil', 'Russia', 'Japan', 'Mexico') )
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.