2017-08-04 123 views
3

我无法使用pyplot.hist函数在同一图上绘制2个直方图。对于每个binning间隔,我希望2个小节在bin(Python 3.6用户)之间居中。为了说明这一点,这里有一个例子:Python:将bin边缘之间的条对齐为双直方图

import numpy as np 
from matplotlib import pyplot as plt 

bin_width=1 

A=10*np.random.random(100) 
B=10*np.random.random(100) 

bins=np.arange(0,np.round(max(A.max(),B.max())/bin_width)*bin_width+2*bin_width,bin_width) 

fig = plt.figure() 
ax = fig.add_subplot(111) 

ax.hist(A,bins,color='Orange',alpha=0.8,rwidth=0.4,align='mid',label='A') 

ax.hist(B,bins,color='Orange',alpha=0.8,rwidth=0.4,align='mid',label='B') 

ax.legend() 
ax.set_ylabel('Count') 

我得到这个:

Histogram_1

A和B系列是重叠的,这是不好的。明知道有的只是3“对齐”选项,(集中在左单元,2个箱中,集中在右单元),我看不是修改的垃圾箱没有其他选择,加入:

bins-=0.25*bin_width 

之前绘制A,并补充说:

bins+=0.5*bin_width 

密谋B.这给了我之前:Histogram

那更好!然而,我不得不修改分档,所以它不是一样的A和B.

我搜索了一个简单的方法来使用相同的箱,然后移动第一和第二小区,以便它们正确显示在binning间隔,但我没有找到它。有什么建议?

我希望我能清楚地解释我的问题。

+0

你不能指望像'plt.hist'一个便利的包装要能占到每天不寻常的情况下,有可能。既然你有两个步骤的过程,保持它分开。使用'np.histogram'来计算你喜欢的任何设置的直方图。然后使用'plt.bar'将结果与任何你喜欢的设置进行比较。 – ImportanceOfBeingErnest

+0

伟大的想法,它现在的作品:)谢谢! –

回答

1

正如前面在上面的评论中提到的,你不需要一个hist plot函数。使用numpy直方图函数并用matplotlib的bar函数绘制结果。

根据箱数和数据类型的数量,您可以计算箱宽。蜱你可能会xticks方法调整:

import numpy as np 
import matplotlib.pylab as plt 

A=10*np.random.random(100) 
B=10*np.random.random(100) 

bins=20 
# calculate heights and bins for both lists 
ahist, abins = np.histogram(A, bins) 
bhist, bbins = np.histogram(B, abins) 

fig = plt.figure() 
ax = fig.add_subplot(111) 
# calc bin width for two lists 
w = (bbins[1] - bbins[0])/3. 
# plot bars 
ax.bar(abins[:-1]-w/2.,ahist,width=w,color='r') 
ax.bar(bbins[:-1]+w/2.,bhist,width=w,color='orange') 
# adjsut xticks 
plt.xticks(abins[:-1], np.arange(bins)) 

plt.show() 

enter image description here