折线图echarts type=time 数据不显示

113 阅读1分钟

需求前提:Y轴是时间 纵坐标:显示0点到24点的时间。默认显示6个跨度,显示为“0:00,4:00,8:00,12:00,16:00,20:00,24:00”。 注意 对于每个时间字符串,创建一个 Date 对象,并提取小时和分钟信息,存储在 processedData 数组中,因为Y轴得度量是 小时,没有携带上日期,携带上日期得话,数据值范围匹配不到。就会不显示的 下面附上代码

  // 处理数据,提取时间部分并转换为时间戳
  const processedData = lineData.yData.map((time) => {
    const [, timePart] = time.split(' ');
    const [hours, minutes, seconds] = timePart.split(':').map(Number);
    // 这里假设日期为 2000-01-01,仅用于获取时间戳,不影响时间轴展示
    const date = new Date(2000, 0, 1, hours, minutes, seconds);
    return date.getTime();
  });
  return {
    tooltip: {
      show: true,
      trigger: 'axis',
      formatter: function (params) {
        const xValue = params[0].axisValue;
        const date = new Date(params[0].data);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        // return `${hours}:${minutes}:${seconds}`;
        return ` 完成日期 ${xValue} ${hours}:${minutes}:${seconds}`;
      },
    },
    grid: {
      top: '5%',
      left: '3%',
      right: '5%',
      bottom: '0%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: lineData.xData,
        axisLabel: {
          color: '#fff',
        },
      },
    ],
    yAxis: [
      {
        axisLabel: {
          color: '#fff',
          formatter: function (value, index) {
            // 将时间戳转换为时间格式
            const date = new Date(value);
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            if (index > 1 && `${hours}:${minutes}` == '00:00') {
              return '24:00';
            }
            return `${hours}:${minutes}`;
          },
        },
        splitLine: {
          show: true,
        },
        type: 'time', // 设置 Y 轴为时间轴
        min: new Date(2000, 0, 1, 0, 0, 0).getTime(),
        max: new Date(2000, 0, 2, 0, 0, 1).getTime(),
        interval: 4 * 60 * 60 * 1000, // 每 4 小时一个跨度(单位:毫秒)
      },
    ],
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100,
        yAxisIndex: 0,
      },
    ],
    series: [
      {
        itemStyle: {
          color: '#74fd64',
        },
        symbol: 'circle',
        symbolSize: 14,
        name: 'Budget 2011',
        type: 'line',
        lineStyle: {
          color: '#06c305',
        },
        data: processedData,
      },
    ],
  };
}