我正在寻找在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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句