自动更新时ChartJs xAxis顺序不正确

flvtvl50  于 2023-04-30  发布在  Chart.js
关注(0)|答案(1)|浏览(206)

在图表中使用自动更新时。js X轴顺序不正确。
codepen

let dt2str = function (d, as_utc = false) {
  let Y = (as_utc === true ? d.getUTCFullYear() : d.getFullYear()).toString();
  let M = ((as_utc === true ? d.getUTCMonth() : d.getMonth()) + 1)
    .toString()
    .padStart(2, 0);
  let D = (as_utc === true ? d.getUTCDate() : d.getDate())
    .toString()
    .padStart(2, 0);
  let h = (as_utc === true ? d.getUTCHours() : d.getHours())
    .toString()
    .padStart(2, 0);
  let m = (as_utc === true ? d.getUTCMinutes() : d.getMinutes())
    .toString()
    .padStart(2, 0);
  let s = (as_utc === true ? d.getUTCSeconds() : d.getSeconds())
    .toString()
    .padStart(2, 0);
  let dstr = `${Y}-${M}-${D} ${h}:${m}:${s}`;
  return dstr;
};

let ctx = document.getElementById("chart");
let chart = new Chart(ctx, {
  type: "line",
  data: {
    datasets: [
      {
        yAxisID: "yAxis1",
        label: "a",
        data: [],
        borderWidth: 1,
        spanGaps: true,
        tension: 0
      },
      {
        yAxisID: "yAxis2",
        label: "b",
        data: [],
        borderWidth: 1,
        spanGaps: true,
        tension: 0
      }
    ]
  },
  options: {
    scales: {
      x: {
        ticks: {
          maxRotation: 90,
          minRotation: 45
        }
      },
      yAxis1: {
        type: "linear",
        display: true,
        position: "left"
      },
      yAxis2: {
        type: "linear",
        display: true,
        position: "right",
        grid: {
          drawOnChartArea: false
        }
      }
    }
  }
});

setInterval(() => {
  let xtime = dt2str(new Date());
  chart.data.datasets.forEach((d) => {
    d.data.push({ x: xtime, y: Math.floor(Math.random() * 10) });
  });
  chart.update();
}, 2000);

我在论坛中查看的大多数都是因为服务器返回的查询不正确。但在我的示例中,我手动推送数据,这意味着每个新数据都是最新的。
正如您在示例中看到的,最新的x刻度以某种方式出现在最左侧的图表上,而另一个具有正确的顺序。
也由于无法加载任何图表。js插件在浏览器中不使用nodejs的时候,我用一个日期字符串表示x轴。
从我在API中读到的,图表。js不会自动对数据进行排序,所以它应该意味着最后一次推送是最新的tick,应该出现在右侧。

uyto3xhc

uyto3xhc1#

不要自己格式化日期/时间,而是将x轴定义为Time Cartesian Axis并使用可用的Chart之一。js date adapters.
请看一下修改后的可运行代码,看看它如何与Luxon adapter一起工作。

let chart = new Chart('chart', {
  type: "line",
  data: {
    datasets: [
      {
        yAxisID: "yAxis1",
        label: "a",
        data: [],
        borderWidth: 1,
        spanGaps: true,
        tension: 0
      },
      {
        yAxisID: "yAxis2",
        label: "b",
        data: [],
        borderWidth: 1,
        spanGaps: true,
        tension: 0
      }
    ]
  },
  options: {
    scales: {
      x: {
        type: 'time',
          time: {       
            unit: 'second',              
            displayFormats: {
              second: 'yyyy-MM-dd HH:mm:ss',
            },
            tooltipFormat: 'yyyy-MM-dd HH:mm:ss' 
        },
        ticks: {
          maxRotation: 90,
          minRotation: 45
        }
      },
      yAxis1: {
        type: "linear",
        display: true,
        position: "left"
      },
      yAxis2: {
        type: "linear",
        display: true,
        position: "right",
        grid: {
          drawOnChartArea: false
        }
      }
    }
  }
});

setInterval(() => {
  chart.data.datasets.forEach((d) => {
    d.data.push({ x: new Date(), y: Math.floor(Math.random() * 10) });
  });
  chart.update();
}, 2000);
<script src="https://cdn.jsdelivr.net/npm/chart.js@^4"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@^3"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@^1"></script>
<canvas id="chart"></canvas>

相关问题