如何为Matplotlib直方图各区间添加求和及均值堆叠柱形?
解决方案
要添加基于前三个柱形求和或均值的第四根柱形,你需要先获取前三个数据集在每个bin的统计值,再手动绘制第四个柱。以下是两种场景的实现代码:
场景1:第四根柱为前三者的求和值
import numpy as np import matplotlib.pyplot as plt np.random.seed(19680801) n_bins = 20 x = np.random.randn(1000, 3) fig, ax0 = plt.subplots(nrows=1, ncols=1) colors = ['red', 'black', 'blue'] # 绘制前三个直方图,同时获取每个bin的密度值、bin边缘和图形对象 counts, bins, patches = ax0.hist(x, n_bins, density=True, histtype='bar', color=colors, label=colors) # 计算每个bin内三个柱形的求和值 sum_counts = counts.sum(axis=0) # 确定每个bin的中心位置和宽度,保证和原有柱形对齐 bin_width = bins[1] - bins[0] x_pos = bins[:-1] + bin_width / 2 # 绘制第四根求和柱形 ax0.bar(x_pos, sum_counts, width=bin_width, color='green', alpha=0.7, label='Sum') ax0.legend(prop={'size': 10}) ax0.set_title('Bars with Sum Column') fig.tight_layout() plt.show()
场景2:第四根柱为前三者的均值
import numpy as np import matplotlib.pyplot as plt np.random.seed(19680801) n_bins = 20 x = np.random.randn(1000, 3) fig, ax0 = plt.subplots(nrows=1, ncols=1) colors = ['red', 'black', 'blue'] # 绘制前三个直方图,同时获取每个bin的密度值、bin边缘和图形对象 counts, bins, patches = ax0.hist(x, n_bins, density=True, histtype='bar', color=colors, label=colors) # 计算每个bin内三个柱形的均值 mean_counts = counts.mean(axis=0) # 确定每个bin的中心位置和宽度,保证和原有柱形对齐 bin_width = bins[1] - bins[0] x_pos = bins[:-1] + bin_width / 2 # 绘制第四根均值柱形 ax0.bar(x_pos, mean_counts, width=bin_width, color='orange', alpha=0.7, label='Mean') ax0.legend(prop={'size': 10}) ax0.set_title('Bars with Mean Column') fig.tight_layout() plt.show()
关键说明
counts是形状为(3, n_bins)的数组,每一行对应一个原始数据集在每个bin的密度值sum(axis=0)对每个bin的三个数值求和,mean(axis=0)计算每个bin的均值- 使用
ax0.bar()手动绘制第四根柱,确保其x位置和宽度与前三个柱形完全对齐
内容的提问来源于stack exchange,提问作者Redhwan
相关产品推荐
相关产品推荐

