簡體   English   中英

Matplotlib:如何使兩個直方圖具有相同的bin寬度?

[英]Matplotlib: How to make two histograms have the same bin width?

我花了一些時間在搜索互聯網上尋找答案,我也試着尋找答案,但我覺得我沒有正確的術語......如果這是重復的,請原諒我一些已知的問題,我很樂意刪除我的帖子並轉而參考該帖子!

無論如何,我試圖在Matplotlib中的同一個圖上繪制兩個直方圖。 我的兩個數據源是500個元素長的列表。 為了說明我面臨的問題,請看下圖:

不均勻的直方圖

如您所見,直方圖在默認參數下具有不均勻的箱尺寸,即使箱的數量相同。 我想保證兩個直方圖的bin寬度是相同的。 有什么方法可以做到這一點嗎?

提前致謝!

我認為,對於大多數情況而言,一致的方法可以輕松地工作,而不必擔心每個數據集的分布范圍,將數據集放在一起,確定二進制數邊緣,然后繪制:

a=np.random.random(100)*0.5 #a uniform distribution
b=1-np.random.normal(size=100)*0.1 #a normal distribution 
bins=np.histogram(np.hstack((a,b)), bins=40)[1] #get the bin edges
plt.hist(a, bins)
plt.hist(b, bins)

在此輸入圖像描述

我猜你可以使用range參數和bin參數為兩個數據集提供相同的bin大小。

plt.hist(x, bins=n, range=(a,b))

如果你保持(ba)/n的比例相同,你應該最終使用相同的箱尺寸。

您應該使用hist返回的值中的bins

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)

兩個具有相同分級的matplotlib直方圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM