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

技术求助:基于直方图绘制平均速度,将各分箱平均速度设为分箱颜色

嗨,这个需求其实很好实现,核心思路就是先算出每个分箱里的平均速度,再把这些平均值映射成对应的颜色给每个柱子上色就行。我用Python的matplotlib给你写个完整的可运行示例,你可以直接参考着适配自己的数据:

import matplotlib.pyplot as plt
import numpy as np

# 先模拟一组速度数据,你把这部分换成自己的真实数据就行
np.random.seed(42)
speeds = np.concatenate([np.random.normal(20, 5, 300), 
                         np.random.normal(40, 8, 200),
                         np.random.normal(60, 6, 150)])

# 第一步:绘制基础直方图,获取分箱边界和柱子对象
n, bins, patches = plt.hist(speeds, bins=10, edgecolor='black')

# 第二步:遍历每个分箱,计算箱内数据的平均速度
bin_means = []
for i in range(len(bins)-1):
    # 筛选当前分箱内的所有速度数据
    current_bin_data = speeds[(speeds >= bins[i]) & (speeds < bins[i+1])]
    # 计算平均值,空分箱就设为0避免报错
    if len(current_bin_data) > 0:
        bin_mean = np.mean(current_bin_data)
    else:
        bin_mean = 0
    bin_means.append(bin_mean)

# 第三步:把平均速度映射成颜色
# 先把平均值归一化到0-1范围,方便颜色映射
norm = plt.Normalize(min(bin_means), max(bin_means))
# 选个颜色映射,viridis是比较常用的,你也可以换plasma、coolwarm这些
cmap = plt.cm.viridis

# 给每个柱子设置对应的颜色
for patch, mean_val in zip(patches, bin_means):
    patch_color = cmap(norm(mean_val))
    patch.set_facecolor(patch_color)

# 添加颜色条,让读者能看懂颜色对应的平均速度
sm = plt.cm.ScalarMappable(norm=norm, cmap=cmap)
sm.set_array([])
plt.colorbar(sm, label='Average Speed in Bin')

# 最后完善图表的标签和标题
plt.xlabel('Speed')
plt.ylabel('Number of Samples')
plt.title('Speed Histogram Colored by Bin Average')

plt.show()

关键细节说明:

  • plt.hist()返回的patches是每个直方图柱子的对象,我们可以逐个修改它们的填充色;
  • Normalize()用来把平均速度的数值范围缩放到0-1,这样颜色映射函数才能正确生成颜色;
  • 如果你的数据是存在pandas DataFrame里的,也可以用分组统计的方式先算出每个分箱的平均值,再对应上色:
import pandas as pd

# 假设你的数据在df的'speed'列里
df = pd.DataFrame({'speed': speeds})
# 给数据分箱
df['speed_bin'] = pd.cut(df['speed'], bins=10)
# 计算每个分箱的平均速度
bin_means = df.groupby('speed_bin')['speed'].mean().tolist()

# 后面的上色步骤和上面完全一样,直接遍历patches和bin_means就行

另外要注意如果有分箱是空的(没有数据),记得做个判断避免计算平均值时报错,我示例里已经加了这个处理。颜色映射也可以根据你的需求换,比如如果平均速度有正负差异,用coolwarm这种冷暖对比的映射会更直观。

内容的提问来源于stack exchange,提问作者Fred Geo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 06:43:22