繁体   English   中英

matplotlib(多个)直方图中的奇怪行为

[英]Strange behavior in matplotlib (multiple) histograms

我尝试使用标准方法在同一画布上绘制两个直方图:

    plt.figure(figsize=(8,6))
    plt.hist(samp_1_I, label=['Female'], alpha=0.5)
    plt.hist(samp_0_I, label=['Male'], alpha=0.5)
    plt.tick_params(axis='both', which='major', labelsize=18)
    plt.legend(fontsize=18)
    plt.show()

结果是: 在此处输入图片说明 如果您注意到,直方图的“条形”没有朝着末端(最右边)对齐。 如何解决? 谁看过这个吗?

横轴是有理数[0,1],默认情况下将其装箱成0.1的10箱。 我不明白为什么两个组的栏不像开始时那样对齐。

如果要使用binwidth 0.1设置10个bin,则需要在调用plt.hist提供这些bin。

import matplotlib.pyplot as plt
import numpy as np

samp_1_I = np.random.rand(14)
samp_0_I = np.random.rand(17)

bins= np.arange(11)/10.

plt.figure(figsize=(8,6))
plt.hist(samp_1_I, bins=bins, label=['Female'], alpha=0.5)
plt.hist(samp_0_I, bins=bins, label=['Male'], alpha=0.5)
plt.tick_params(axis='both', which='major', labelsize=18)
plt.legend(fontsize=18)
plt.show()


从评论中回答问题:使用normed=True可以得到归一化的频率,即每个仓宽上的总和乘以该频率就是1

sample = np.random.rand(14)
bins= np.arange(11)/10.
hist, _bins = np.histogram(sample, bins=bins, normed = True)
print hist
print np.sum ( hist * np.diff(bins) ) # This prints 1.0

即使纸箱宽度不同,也是如此。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM