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

如何基于仪器扫描的x、y点及对应角度值生成热力图?

散点数据生成热力图的可行方案及错误修复

现有仪器扫描得到的散点数据:

  • x_points:一维数组,存储x坐标
  • y_points:一维数组,存储y坐标
  • philist:一维数组,对应每个(x,y)点的检测角度值

尝试三种方法均报错,以下是错误分析及解决方案:

错误原因分析

1. griddata报错:different number of values and points

  • 核心问题:
    • 输入griddata的points参数格式错误,需传入**(N,2)形状的二维数组**,而非两个独立的一维数组
    • 第三个参数应为要插值的规则网格,而非原始散点,否则失去插值意义
    • 需先确认x_points、y_points、philist三者长度完全一致

2. pcolormesh报错:not enough values to unpack (expected 2, got 1)

  • pcolormesh要求输入的X、Y是二维网格数组(由meshgrid生成),C是对应形状的二维数值数组,而你传入的均为一维数组,不符合参数要求

可行解决方案

方案1:griddata插值+contourf(规则网格热力图)

先将散点插值到规则网格,再绘制填充等高线图,适合需要平滑效果的场景:

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata

# 确保数据长度一致(先做检查)
assert len(x_points) == len(y_points) == len(philist), "数据长度不匹配"

# 1. 准备原始点数据
points = np.column_stack((x_points, y_points))
values = np.array(philist)

# 2. 生成规则网格
xi = np.linspace(min(x_points), max(x_points), 100)
yi = np.linspace(min(y_points), max(y_points), 100)
xi, yi = np.meshgrid(xi, yi)

# 3. 插值(可选method='linear'/'cubic'/'nearest',根据需求选择)
zi = griddata(points, values, (xi, yi), method='cubic')

# 4. 绘制热力图
fig, ax = plt.subplots()
CS = ax.contourf(xi, yi, zi, 15, cmap=plt.cm.rainbow)
plt.colorbar(CS, label='检测角度')
ax.set_xlabel('X坐标')
ax.set_ylabel('Y坐标')
plt.show()

方案2:tricontourf(直接用散点绘制,无需插值)

适合不规则分布的散点,直接基于三角剖分绘制热力图,保留原始数据分布:

import numpy as np
import matplotlib.pyplot as plt

# 确保数据长度一致
assert len(x_points) == len(y_points) == len(philist), "数据长度不匹配"

fig, ax = plt.subplots()
# 直接绘制三角剖分填充图
CS = ax.tricontourf(x_points, y_points, philist, 15, cmap=plt.cm.rainbow)
plt.colorbar(CS, label='检测角度')
ax.set_xlabel('X坐标')
ax.set_ylabel('Y坐标')
plt.show()

方案3:散点热力图(用点的颜色和大小表示数值)

如果不需要填充的热力面,可直接用散点图的颜色映射展示数值:

import numpy as np
import matplotlib.pyplot as plt

# 确保数据长度一致
assert len(x_points) == len(y_points) == len(philist), "数据长度不匹配"

fig, ax = plt.subplots()
sc = ax.scatter(x_points, y_points, c=philist, cmap=plt.cm.rainbow, vmin=-np.abs(philist).max(), vmax=np.abs(philist).max())
plt.colorbar(sc, label='检测角度')
ax.set_xlabel('X坐标')
ax.set_ylabel('Y坐标')
plt.show()

内容的提问来源于stack exchange,提问作者Tristan Forks

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 14:34:54