如何在chart.js中为折线图使用type:'time'?

dxxyhpgq  于 12个月前  发布在  Chart.js
关注(0)|答案(1)|浏览(134)

对于数据中的一项,y轴显示适当的数字。
图表中没有显示任何内容。它只显示x和y轴,但图表内部没有任何内容。需要执行哪些操作才能在图表中显示数据?
当我在数据中添加第二项时,y轴发生变化,显示0到1。为什么会发生这种情况?

import Chart from 'chart.js/auto'
import 'chartjs-adapter-date-fns';

const timeScaleChart = () => {
  const data = [
    { year: "2022-05-01", count: 30, borderColor: "red", backgroundColor: 'blue' },
    { year: "2026-05-01", count: 40, borderColor: "red", backgroundColor: 'blue' },
  ];

  new Chart(
    document.getElementById('timeline'),
    {
      type: 'line',
      options: {
        plugins: {
          title: {
            text: 'Chart.js Time Scale',
            display: true
          }
        },
        scales: {
          x: {
            type: 'time',
            time: {
              unit: 'day'
            },
            title: {
              display: true,
              text: 'Date'
            }
          },
          y: {
            title: {
              display: true,
              text: 'count'
            }
          }
        },
      },
      data: {
      labels: data.map(row => row.year),
        datasets: [
          {
            label: 'Time scale',
            data: [{
              x: data.map(row => row.year),
              y: data.map(row => row.count),
            }],
            borderColor: data.map(row => row.borderColor),
            backgroundColor: data.map(row => row.backgroundColor),
            fill: false,
          }
        ]
      }
    }
  );
};

export default timeScaleChart;

字符串

ca1c2owp

ca1c2owp1#

我需要转换数据。

const transformedData = data.map(({ year, count }) => ({ x: year, y: count }));

字符串
使用data: transformedData

相关问题