web-dev-qa-db-ja.com

matplotlibを使って2つのヒストグラムを同時にプロットする

ファイルのデータを使用してヒストグラムプロットを作成しましたが、問題ありません。今度は同じヒストグラム内の別のファイルからのデータを重ね合わせたいので、次のようにします。

n,bins,patchs = ax.hist(mydata1,100)
n,bins,patchs = ax.hist(mydata2,100)

しかし問題は、各区間について、最も高い値を持つ小節だけが表示され、他の小節は非表示になることです。どうやって両方のヒストグラムを異なる色で同時にプロットできるのでしょうか。

179
Open the way

ここにあなたは実用的な例を持っています:

import random
import numpy
from matplotlib import pyplot

x = [random.gauss(3,1) for _ in range(400)]
y = [random.gauss(4,2) for _ in range(400)]

bins = numpy.linspace(-10, 10, 100)

pyplot.hist(x, bins, alpha=0.5, label='x')
pyplot.hist(y, bins, alpha=0.5, label='y')
pyplot.legend(loc='upper right')
pyplot.show()

enter image description here

340
joaquin

受け入れられた答えは重なり合うバーを持つヒストグラムのためのコードを与えます、しかしあなたが(私がしたように)あなたがそれぞれのバーを横に並べたいならば、以下の変化を試してください:

import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-deep')

x = np.random.normal(1, 2, 5000)
y = np.random.normal(-1, 3, 2000)
bins = np.linspace(-10, 10, 30)

plt.hist([x, y], bins, label=['x', 'y'])
plt.legend(loc='upper right')
plt.show()

enter image description here

参照: http://matplotlib.org/examples/statistics/histogram_demo_multihist.html

EDIT [2018/03/16]:@stochastic_zeitgeistが示唆しているように、異なるサイズの配列をプロットできるように更新しました

120
Gustavo Bezerra

標本サイズが異なる場合、単一のy軸と分布を比較するのは難しいかもしれません。例えば:

import numpy as np
import matplotlib.pyplot as plt

#makes the data
y1 = np.random.normal(-2, 2, 1000)
y2 = np.random.normal(2, 2, 5000)
colors = ['b','g']

#plots the histogram
fig, ax1 = plt.subplots()
ax1.hist([y1,y2],color=colors)
ax1.set_xlim(-10,10)
ax1.set_ylabel("Count")
plt.tight_layout()
plt.show()

hist_single_ax

この場合、2つのデータセットを異なる軸にプロットすることができます。これを行うには、matplotlibを使用してヒストグラムデータを取得し、軸を消去してから、2つの別々の軸に重ねてプロットします(それらが重ならないようにビンの端を移動します)。

#sets up the axis and gets histogram data
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.hist([y1, y2], color=colors)
n, bins, patches = ax1.hist([y1,y2])
ax1.cla() #clear the axis

#plots the histogram data
width = (bins[1] - bins[0]) * 0.4
bins_shifted = bins + width
ax1.bar(bins[:-1], n[0], width, align='Edge', color=colors[0])
ax2.bar(bins_shifted[:-1], n[1], width, align='Edge', color=colors[1])

#finishes the plot
ax1.set_ylabel("Count", color=colors[0])
ax2.set_ylabel("Count", color=colors[1])
ax1.tick_params('y', colors=colors[0])
ax2.tick_params('y', colors=colors[1])
plt.tight_layout()
plt.show()

hist_twin_ax

20
Andrew

データのサイズが異なる場合に、同じプロット上に2つのヒストグラムを棒で並べてプロットする簡単な方法は次のとおりです。

def plotHistogram(p, o):
    """
    p and o are iterables with the values you want to 
    plot the histogram of
    """
    plt.hist([p, o], color=['g','r'], alpha=0.8, bins=50)
    plt.show()

Gustavo Bezerraの答えを補完するものとして

各ヒストグラムを正規化したい の場合はnormedname__、mplの場合はdensity= = normed/density=Trueを使用することはできませんが、重みを設定する必要があります。代わりに各値に対して:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.normal(1, 2, 5000)
y = np.random.normal(-1, 3, 2000)
x_w = np.empty(x.shape)
x_w.fill(1/x.shape[0])
y_w = np.empty(y.shape)
y_w.fill(1/y.shape[0])
bins = np.linspace(-10, 10, 30)

plt.hist([x, y], bins, weights=[x_w, y_w], label=['x', 'y'])
plt.legend(loc='upper right')
plt.show()

enter image description here

比較として、デフォルトの重みとdensity=Trueを持つまったく同じxname__とyname__ベクトル

enter image description here

5
jojo

棒グラフがほしいと思うかもしれません:

あるいは、サブプロットを使用することもできます。

3
carl

binsによって返される値からhistを使用する必要があります。

import numpy as np
import matplotlib.pyplot as plt

foo = np.random.normal(loc=1, size=100) # a normal distribution
bar = np.random.normal(loc=-1, size=10000) # a normal distribution

_, bins, _ = plt.hist(foo, bins=50, range=[-6, 6], normed=True)
_ = plt.hist(bar, bins=bins, alpha=0.5, normed=True)

Two matplotlib histograms with same binning

3
Adrien Renaud

念のためにあなたがパンダ(import pandas as pd)を持っているか、それを使っても大丈夫です:

test = pd.DataFrame([[random.gauss(3,1) for _ in range(400)], 
                     [random.gauss(4,2) for _ in range(400)]])
plt.hist(test.values.T)
plt.show()
2
serv-inc

この質問は以前に回答されましたが、この質問への他の訪問者を助けるかもしれない別の迅速で簡単な回避策を追加したいと思いました。

import seasborn as sns 
sns.kdeplot(mydata1)
sns.kdeplot(mydata2)

いくつかの有用な例は ここ kde対ヒストグラム比較です。

0
Solomon Vimal

ソロモンの答えに触発されたが、ヒストグラムに関連している質問に固執するために、きれいな解決策は以下のとおりです。

sns.distplot(bar)
sns.distplot(foo)
plt.show()

より高いものを最初にプロットするようにしてください。そうでなければ、より高いヒストグラムが切り取られないようにplt.ylim(0,0.45)を設定する必要があります。

0
Sarah