Matplotlib / Seabornを使用して2つの積み重ねられたヒストグラムを並べて描画する方法

Aug 19 2020

以下のコードを使用して、積み重ねられたヒストグラムをいくつか描画しています。私は両方に同じビンエッジを使用しているので、それらはうまく整列されています。

これらを同じチャートに表示するにはどうすればよいですか?つまり、各ビンごとに緑/赤と青/オレンジのバーが並んでいます。

棒グラフを使用して棒の幅を計算することを提案する、これに似た多くの質問と回答を見ましたが、これは、少なくとも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)

回答

1 PéterLeéh Aug 19 2020 at 16:25

さて、私plt.barはここであなたの最善の策だと思います。積み上げヒストグラムを作成するには、そのbottom引数を使用できます。この元のmatplotlibの例のように、2つの棒グラフを並べて表示するには、x値を少しずらすことができます。width

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()

これは次を返します:

BossaNova Aug 19 2020 at 16:05

これは、2つのヒストグラムが表示され、各ビンに専用の場所が並んでいる簡単な例(ヒストグラムは積み重ねられていない)です。

# 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')