如何在同一画布上创建并绘制4组原始数据的多系列直方图
基于四组独立数组绘制多系列直方图的实现方案
你拥有的四组独立数据如下:
- 25℃变更前:
data_25_before = [1, 2, 3,..., 10] - 79℃变更前:
data_79_before = [0.5, 1, 1.5,..., 5] - 25℃变更后:
data_25_after = [5, 6, 7,..., 15] - 79℃变更后:
data_79_after = [2.5, 3, 3.5,..., 7.5]
以下是两种常用Python工具的实现方案,分别支持叠加式和并排式多系列直方图:
使用Matplotlib绘制
Matplotlib通过多次调用hist()函数实现多系列展示,可通过透明度、偏移量区分各组数据。
叠加式直方图
import matplotlib.pyplot as plt import numpy as np # 定义数据集 data_25_before = np.arange(1, 11) data_79_before = np.arange(0.5, 5.5, 0.5) data_25_after = np.arange(5, 16) data_79_after = np.arange(2.5, 8, 0.5) # 统一设置直方图区间 bins = np.linspace(0, 16, 17) # 绘制各组直方图,设置透明度和标签 plt.hist(data_25_before, bins=bins, alpha=0.6, label='25℃ 变更前') plt.hist(data_79_before, bins=bins, alpha=0.6, label='79℃ 变更前') plt.hist(data_25_after, bins=bins, alpha=0.6, label='25℃ 变更后') plt.hist(data_79_after, bins=bins, alpha=0.6, label='79℃ 变更后') # 添加图表元素 plt.legend() plt.title('不同温度下变更前后数据的直方图') plt.xlabel('数据值') plt.ylabel('频数') plt.show()
并排式直方图
import matplotlib.pyplot as plt import numpy as np # 定义数据集 data_25_before = np.arange(1, 11) data_79_before = np.arange(0.5, 5.5, 0.5) data_25_after = np.arange(5, 16) data_79_after = np.arange(2.5, 8, 0.5) bins = np.linspace(0, 16, 9) bin_width = bins[1] - bins[0] offset = bin_width / 5 # 调整偏移量避免组间重叠 # 绘制各组并排直方图 plt.hist(data_25_before, bins=bins - 1.5*offset, width=offset, alpha=0.8, label='25℃ 变更前') plt.hist(data_79_before, bins=bins - 0.5*offset, width=offset, alpha=0.8, label='79℃ 变更前') plt.hist(data_25_after, bins=bins + 0.5*offset, width=offset, alpha=0.8, label='25℃ 变更后') plt.hist(data_79_after, bins=bins + 1.5*offset, width=offset, alpha=0.8, label='79℃ 变更后') # 添加图表元素 plt.legend() plt.title('不同温度下变更前后数据的并排直方图') plt.xlabel('数据值') plt.ylabel('频数') plt.show()
使用Seaborn绘制
Seaborn适合结构化数据,可将四组数据合并为DataFrame后快速绘制多系列直方图。
import seaborn as sns import pandas as pd import numpy as np # 定义数据集 data_25_before = np.arange(1, 11) data_79_before = np.arange(0.5, 5.5, 0.5) data_25_after = np.arange(5, 16) data_79_after = np.arange(2.5, 8, 0.5) # 构造结构化DataFrame df = pd.DataFrame({ '数值': np.concatenate([data_25_before, data_79_before, data_25_after, data_79_after]), '分组': ['25℃ 变更前']*len(data_25_before) + ['79℃ 变更前']*len(data_79_before) + ['25℃ 变更后']*len(data_25_after) + ['79℃ 变更后']*len(data_79_after) }) # 绘制叠加式直方图 sns.histplot(data=df, x='数值', hue='分组', bins=16, alpha=0.6, multiple='layer') plt.title('不同温度下变更前后数据的直方图') plt.xlabel('数据值') plt.ylabel('频数') plt.show() # 绘制并排式直方图 sns.histplot(data=df, x='数值', hue='分组', bins=16, alpha=0.8, multiple='dodge') plt.title('不同温度下变更前后数据的并排直方图') plt.xlabel('数据值') plt.ylabel('频数') plt.show()
内容的提问来源于stack exchange,提问作者Anthony The Nguyen
相关产品推荐
相关产品推荐

