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

如何根据第三值设置Highcharts散点图数据点颜色?

实现Highcharts单数据点按风速自定义配色的风向散点图

不需要拆分12个蒲福风级系列,直接给单个数据点设置color属性就能实现需求,核心思路是在数据预处理阶段根据风速计算每个点的颜色,再传入Highcharts配置。

步骤1:数据预处理与颜色计算

先准备原始数据(包含时间、风向、风速),然后遍历每个数据点,根据风速阈值或渐变逻辑生成对应颜色:

// 模拟原始数据集:时间、风向(0-360°)、风速(m/s)
const rawData = [
  { time: '2024-05-01 00:00', direction: 45, speed: 2.5 },
  { time: '2024-05-01 01:00', direction: 135, speed: 8 },
  { time: '2024-05-01 02:00', direction: 225, speed: 16 },
  { time: '2024-05-01 03:00', direction: 315, speed: 22 },
  // 更多数据...
];

// 处理数据,为每个点分配颜色
const chartData = rawData.map(item => {
  let pointColor;
  
  // 按风速区间设置固定颜色(可自定义阈值)
  if (item.speed < 5) {
    pointColor = '#27ae60'; // 绿色:低风速
  } else if (item.speed < 15) {
    pointColor = '#f39c12'; // 黄色:中等风速
  } else {
    pointColor = '#e74c3c'; // 红色:高风速
  }

  return {
    x: new Date(item.time).getTime(), // 转换为时间戳适配时间轴
    y: item.direction,
    color: pointColor,
    speed: item.speed, // 保留风速用于tooltip展示
    tooltip: {
      pointFormat: `时间: {point.x:%Y-%m-%d %H:%M}<br>风向: {point.y}°<br>风速: {point.speed} m/s`
    }
  };
});

如果需要平滑的颜色渐变(比如从绿到红线性过渡),可以用Highcharts内置的颜色插值功能:

// 生成渐变颜色的工具函数
function getGradientColor(speed, minSpeed = 0, maxSpeed = 30) {
  // 将风速归一到0-1范围
  const normalizedSpeed = Math.max(0, Math.min(1, (speed - minSpeed) / (maxSpeed - minSpeed)));
  // 从绿色渐变到红色
  const startColor = Highcharts.Color('#27ae60');
  const endColor = Highcharts.Color('#e74c3c');
  return startColor.tweenTo(endColor, normalizedSpeed).get();
}

// 在数据处理时替换颜色赋值:
// pointColor = getGradientColor(item.speed);

步骤2:初始化Highcharts图表

将处理好的数据集传入单系列配置,即可实现单数据点独立配色的散点图:

Highcharts.chart('wind-chart-container', {
  chart: {
    type: 'scatter',
    height: 400
  },
  title: {
    text: '风向-时间散点图(风速配色)'
  },
  xAxis: {
    type: 'datetime',
    title: { text: '时间' },
    dateTimeLabelFormats: {
      hour: '%H:%M',
      day: '%m-%d'
    }
  },
  yAxis: {
    title: { text: '风向 (°)' },
    min: 0,
    max: 360,
    tickInterval: 45, // 每45度显示一个刻度
    labels: {
      formatter: function() {
        // 风向刻度显示方位(可选)
        const directions = ['北', '东北', '东', '东南', '南', '西南', '西', '西北'];
        return directions[this.value / 45];
      }
    }
  },
  tooltip: {
    shared: false
  },
  series: [{
    name: '观测数据',
    data: chartData,
    marker: {
      radius: 6 // 调整数据点大小
    }
  }]
});

优势说明

  • 相比拆分12个系列,单系列+单点配色的方式更简洁,避免图表配置冗余;
  • 颜色逻辑集中在数据预处理阶段,后续调整风速阈值或配色方案更便捷;
  • Tooltip和交互逻辑统一,无需处理多系列的复杂配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 17:31:15