python - 如何使用 Matplotlib/Seaborn 并排绘制两个堆叠直方图

标签 python matplotlib seaborn

我正在使用下面的代码绘制几个堆叠的直方图。 我为两者使用了相同的 bin 边缘,因此它们可以很好地对齐。

如何将这些显示在同一张图表上? IE。每个箱子都有一个绿色/红色和一个蓝色/橙色条 - 并排。

看到很多类似this的问答建议使用条形图并计算条形的宽度,但这似乎应该开箱即用,至少在 matplotlib 中是这样。

另外,我可以直接用 seaborn 绘制堆叠直方图吗?我找不到方法。

plt.hist( [correct_a, incorrect_a], bins=edges, stacked=True, color=['green', 'red'], rwidth=0.95, alpha=0.5)

enter image description here

plt.hist( [correct_b, incorrect_b], bins=edges, stacked=True, color=['green', 'red'], rwidth=0.95, alpha=0.5)

enter image description here

最佳答案

嗯,我想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

关于python - 如何使用 Matplotlib/Seaborn 并排绘制两个堆叠直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63483196/

相关文章:

python - 如何从 AWS 中的 SQS 队列接收多于 1 条消息?

python - KL(Kullback-Leibler)距离与 Python 中的直方图平滑

python - matplotlib 中具有重叠点的散点图的可视化

python - 如何更改 seaborn implot 中不同回归线的线条样式?

python - 姓名或头衔方面

python - 使用 if 语句的 meshgrid 和用户定义函数的真值不明确

python - 在数组中定义多个绘图对象并在 matplotlib 动画中更新

python - 如何将 seaborn 图保存为 svg 或 png

python - 将 DataFrame 的列设置为 FacetGrid 图形的行

python - 在类 __init__ 上定义 aiohttp ClientSession 以供以后重用