Matplotlib 中如何同时绘制两个直方图

我们可以在一个图中同时绘制两个直方图。下面显示了创建带有和不带有重叠条形图的两个直方图的方法。

两个直方图,无重叠条

示例代码:

import numpy as np
import matplotlib.pyplot as plt
a = np.random.normal(0, 3, 3000)
b = np.random.normal(2, 4, 2000)
bins = np.linspace(-10, 10, 20)
plt.hist([a, b], bins, label=['a', 'b'])
plt.legend(loc='upper left')
plt.show()

Matplotlib 中如何同时绘制两个直方图

带重叠条的两个直方图

示例代码:

import numpy as np
import matplotlib.pyplot as plt
a = np.random.normal(0, 3, 1000)
b = np.random.normal(2, 4, 900)
bins = np.linspace(-10, 10, 50)
plt.hist(a, bins, alpha = 0.5, label='a')
plt.hist(b, bins, alpha = 0.5, label='b')
plt.legend(loc='upper left')
plt.show()

Matplotlib 中如何同时绘制两个直方图

当我们两次调用 plt.hist 分别绘制直方图时,两个直方图将具有重叠的条,如你在上面看到的。

alpha 属性指定绘图的透明度。0.0 是完全透明的,而 1.0 是完全不透明的。

当两个直方图的 alpha 均设为 0.5 时,重叠区域将显示组合颜色。但是,如果 alpha0.0(默认值),重叠的条仅显示两个直方图中较高值的颜色,而另一种颜色则被隐藏,如下所示。

Matplotlib 中如何同时绘制两个直方图