Pandasの複数のヒストグラム 質問する

Pandasの複数のヒストグラム 質問する

「Think Stats」という本から引用した次のヒストグラム (下の画像を参照) を作成したいと思います。ただし、同じプロットに表示できません。各 DataFrame は独自のサブプロットを取得します。

次のコードがあります:

import nsfg
import matplotlib.pyplot as plt
df = nsfg.ReadFemPreg()
preg = nsfg.ReadFemPreg()
live = preg[preg.outcome == 1]

first = live[live.birthord == 1]
others = live[live.birthord != 1]

#fig = plt.figure()
#ax1 = fig.add_subplot(111)

first.hist(column = 'prglngth', bins = 40, color = 'teal', \
           alpha = 0.5)
others.hist(column = 'prglngth', bins = 40, color = 'blue', \
            alpha = 0.5)
plt.show()

上記のコードは、次のとおり ax = ax1 を使用すると機能しません。パンダの複数のプロットがヒストとして機能しないこの例も私が必要としていることを実行しません:パンダを使用して複数のヒストグラムを重ねるコードをそのまま使用すると、ヒストグラムを含む 2 つのウィンドウが作成されます。これらを組み合わせる方法はありますか?

最終的な図の見た目の例を以下に示します。ここに画像の説明を入力してください

ベストアンサー1

私の知る限り、pandas はこの状況に対処できません。pandas のプロット方法はすべて利便性のためだけのものなので、問題ありません。matplotlib を直接使用する必要があります。私のやり方は次のとおりです。

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import pandas
#import seaborn
#seaborn.set(style='ticks')

np.random.seed(0)
df = pandas.DataFrame(np.random.normal(size=(37,2)), columns=['A', 'B'])
fig, ax = plt.subplots()

a_heights, a_bins = np.histogram(df['A'])
b_heights, b_bins = np.histogram(df['B'], bins=a_bins)

width = (a_bins[1] - a_bins[0])/3

ax.bar(a_bins[:-1], a_heights, width=width, facecolor='cornflowerblue')
ax.bar(b_bins[:-1]+width, b_heights, width=width, facecolor='seagreen')
#seaborn.despine(ax=ax, offset=10)

そして、次のようになります。ここに画像の説明を入力してください

おすすめ記事