You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 20:12:48