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

能否基于两个XMLHttpRequest变量绘制湿度-温度关联图表?

实现温度与湿度的关联图表方案

你的问题核心在于原来的代码是分别独立获取温度和湿度数据,导致两者无法同步配对,而且关联图表需要的是[温度值, 湿度值]这样的成对数据,不是各自基于时间的序列。以下是具体的修正方案:

关键改动说明

  • 不再分开请求温度和湿度,改为请求一个能同时返回当前温湿度的接口(如果后端不支持,也可以前端同时发起两个请求并等待都返回后再处理,但推荐后端统一返回,避免数据时序差)
  • 把X轴从datetime类型改为linear,因为X轴是温度数值,不是时间
  • 图表类型推荐用scatter(散点图,更适合展示变量间的关联关系),也可以保留line但意义不大
  • 维护成对的温湿度数据点,超过数量限制时移除最早的点

修改后的完整代码

// 创建温湿度关联图表
var chartCorrelation = new Highcharts.Chart({
  chart: { 
    renderTo: "chart-correlation",
    type: 'scatter' // 散点图,适合展示变量关联;如果要连线可以改成'line'
  },
  title: { text: "温度与湿度关联图" },
  series: [
    {
      showInLegend: false,
      data: [],
    },
  ],
  plotOptions: {
    scatter: { 
      animation: false, 
      dataLabels: { enabled: true, format: '{point.x}°C, {point.y}%' } 
    },
    series: { color: "#059e8a" },
  },
  xAxis: { 
    type: "linear",
    title: { text: "Temperature (Celsius)" }
  },
  yAxis: {
    title: { text: "Humidity (%)" },
  },
  credits: { enabled: false },
});

// 定时获取温湿度数据并更新图表
setInterval(function () {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      // 假设后端返回的是JSON格式:{"temperature": 25.5, "humidity": 60.2}
      var data = JSON.parse(this.responseText);
      var temp = parseFloat(data.temperature);
      var humi = parseFloat(data.humidity);
      
      // 添加成对的[温度, 湿度]数据点
      if (chartCorrelation.series[0].data.length > 40) {
        chartCorrelation.series[0].addPoint([temp, humi], true, true, true);
      } else {
        chartCorrelation.series[0].addPoint([temp, humi], true, false, true);
      }
    }
  };
  // 请求同时返回温湿度的接口,替换成你的实际接口路径
  xhttp.open("GET", "/temperature-humidity", true);
  xhttp.send();
}, 30000);

替代方案(后端无法修改接口时)

如果后端暂时无法提供合并接口,可以用Promise.all同时发起两个请求,等待都返回后再处理:

setInterval(function () {
  Promise.all([
    fetch('/temperature').then(res => res.text()).then(parseFloat),
    fetch('/humidity').then(res => res.text()).then(parseFloat)
  ]).then(([temp, humi]) => {
    if (chartCorrelation.series[0].data.length > 40) {
      chartCorrelation.series[0].addPoint([temp, humi], true, true, true);
    } else {
      chartCorrelation.series[0].addPoint([temp, humi], true, false, true);
    }
  }).catch(err => console.error('获取数据失败:', err));
}, 30000);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 02:10:51