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

Jinku Hu 2023年1月30日 2020年3月28日 Matplotlib Matplotlib Histogram

## 两个直方图，无重叠条

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()

## 带重叠条的两个直方图

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()

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

Author: Jinku Hu

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

## 相关文章 - Matplotlib Histogram

• 如何在 Matplotlib 直方图中手动设置 bin 的大小
• Matplotlib 中为直方图着色