我正在使用以下代码绘制几个堆叠的直方图。 我对两者使用了相同的纸槽边缘,因此它们对齐得很好。
如何将它们显示在同一张图表上?即每个垃圾箱分别有一个绿色/红色和蓝色/橙色的条形图。
我看到了许多与this类似的问题和答案,它们建议使用条形图并计算条形的宽度,但这似乎是应立即使用的,至少在matplotlib中应得到支持
我还能直接用seaborn绘制堆叠的直方图吗?我找不到办法。
plt.hist( [correct_a, incorrect_a], bins=edges, stacked=True, color=['green', 'red'], rwidth=0.95, alpha=0.5)
plt.hist( [correct_b, incorrect_b], bins=edges, stacked=True, color=['green', 'red'], rwidth=0.95, alpha=0.5)
答案 0 :(得分:1)
好吧,我认为plt.bar
是您最好的选择。要创建堆叠的直方图,可以使用其bottom
参数。要并排显示两个条形图,您可以将x
的值移动width
,就像在this原始matplotlib示例中一样:
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(16, 8))
correct_a = np.random.randint(0, 20, 20)
incorrect_a = np.random.randint(0, 20, 20)
correct_b = np.random.randint(0, 20, 20)
incorrect_b = np.random.randint(0, 20, 20)
edges = len(correct_a)
width=0.35
rects1 = ax.bar(np.arange(edges), incorrect_a, width, color="red", label="incorrect_a")
rects2 = ax.bar(np.arange(edges), correct_a, width, bottom=incorrect_a, color='seagreen', label="correct_a")
rects3 = ax.bar(np.arange(edges) + width, incorrect_b, width, color="blue", label="incorrect_b")
rects4 = ax.bar(np.arange(edges) + width, correct_b, width, bottom=incorrect_b, color='orange', label="correct_b")
# placing the ticks to the middle
ticks_aligned = np.arange(edges) + width // 2
ax.set_xticks(np.arange(edges) + width / 2)
ax.set_xticklabels((str(tick) for tick in ticks_aligned))
ax.legend()
这将返回:
答案 1 :(得分:0)
这是一个简单的示例(直方图未堆叠),其中显示了2个直方图,并且每个bin并排放置有专用的位置:
# generating some data for this example:
a = [1,2,3,4,3,4,2,3,4,5,4,3,4,5,4,1,2,3,2,1,3,4,5,6,7,6,5,4,3,4,6,5,4,3,4]
b = [1,2,3,4,5,6,7,6,5,6,7,6,5,4,3,4,5,6,7,6,7,6,7,5,4,3,2,1,3,4,5,6,5,6,5,6,7,6,7]
# plotting 2 histograms with bars centered differently within each bin:
plt.hist(a, bins=5, align='left', rwidth=0.5)
plt.hist(b, bins=5, align='mid', rwidth=0.5, color='r')