📜  如何使用 Matplotlib 在直方图中按组填充颜色?(1)

📅  最后修改于: 2023-12-03 15:23:56.331000             🧑  作者: Mango

如何使用 Matplotlib 在直方图中按组填充颜色?

在数据可视化的过程中,直方图是一个非常常用的方式,它可以帮助我们更清晰地了解数据的分布情况。在 Matplotlib 中,我们可以使用 hist 函数来创建直方图,并使用 color 参数来指定柱子的颜色。

但是当我们需要在直方图中区分每组数据时,单纯地指定柱子的颜色就无法满足我们的需求了。这时候,我们可以使用 hist 函数的 histtype 参数来指定直方图的类型,在 step 类型下,就可以实现按组填充颜色的效果。

下面我们来看看如何具体实现。

创建数据集

首先,我们需要创建一组数据集。在这里,我们使用 Numpy 来生成 5 组随机数据,并使用 Pandas 将它们转换为 DataFrame 格式,以便于后续可视化处理。

import numpy as np
import pandas as pd

np.random.seed(123)
data = {
    'group1': np.random.normal(50, 10, 100),
    'group2': np.random.normal(60, 15, 100),
    'group3': np.random.normal(70, 5, 100),
    'group4': np.random.normal(80, 12, 100),
    'group5': np.random.normal(90, 8, 100)
}
df = pd.DataFrame(data)
创建直方图

接下来,我们使用 Matplotlib 中的 hist 函数来创建直方图,并使用 histtype='step' 参数来指定直方图的类型。

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 6))
ax.hist(df['group1'], bins=20, color='red', alpha=0.5, histtype='step', label='Group 1')
ax.hist(df['group2'], bins=20, color='green', alpha=0.5, histtype='step', label='Group 2')
ax.hist(df['group3'], bins=20, color='blue', alpha=0.5, histtype='step', label='Group 3')
ax.hist(df['group4'], bins=20, color='orange', alpha=0.5, histtype='step', label='Group 4')
ax.hist(df['group5'], bins=20, color='purple', alpha=0.5, histtype='step', label='Group 5')
ax.legend(loc='upper right')
plt.show()

在代码中,我们依次绘制了 5 组数据的直方图,并使用不同的颜色来区分它们。注意,在 histtype='step' 参数下,我们需要连续绘制多个直方图,以便于区分每组数据。

结果展示

运行上述代码,我们可以得到如下的直方图。

hist

从图中可以看出,通过使用 histtype='step' 参数,我们成功地在直方图中实现了按组填充颜色的效果。这样的可视化效果可以更加直观地呈现数据的分布情况,从而帮助我们更好地理解数据。