如何通过 Chart.js 使用时间戳格式化 x 轴?

e_r*_*son 1 html javascript css json chart.js

我想在图表上显示数据库中的温度读数。但是,目前 x 轴显示的值不正确,与我的测试数据集不对应。

x 轴旨在使用时间戳在时域中,相反,该图使用标签“Reddd”中的每个字符作为 x 轴的值。

y 轴是正确的并且对应于测试数据点。

下面的函数包含用于构建图表的 JavaScript 代码。

function makeGraph() {
    const ctx = document.getElementById('canvas').getContext('2d');
    const myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: 'Reddd',
            datasets: [{
                label: 'Temperature',
                data: [{"x": 1647281788963, "y": 22.9}, {"x": 1647281994496, "y": 26.9}, {"x": 1647282200029, "y": 21.9}, {"x": 1647282405562, "y": 24.9}, {"x": 1647282611094, "y": 28.9}],
                backgroundColor: 'transparent',
                borderColor: 'red',
                borderWidth: 2
            }]
        },
        options: {
            scales: {
                x: {
                    type: 'time',
                    time: {
                        // Luxon format string
                        tooltipFormat: 'DD T'

                    },
                    title: {
                        display: true,
                        text: 'Date'
                    }
                },
                y: {
                    title: {
                        display: true,
                        text: 'value'
                    }
                }
            }
        }
    });


}
Run Code Online (Sandbox Code Playgroud)

这是图表的输出: 在此输入图像描述

如果我在语句后不包含字符串labels:,则图表将如下所示: 在此输入图像描述

umi*_*der 6

首先,您不能定义data.labels.

此外,x轴可以定义如下:

x: {
  type: 'time',
  time: {
    unit: 'minute',
    displayFormats: {
      minute: 'DD T'
    },
    tooltipFormat: 'DD T'
  },
  ...
Run Code Online (Sandbox Code Playgroud)

请查看下面修改后的可运行代码,看看它是如何工作的。

x: {
  type: 'time',
  time: {
    unit: 'minute',
    displayFormats: {
      minute: 'DD T'
    },
    tooltipFormat: 'DD T'
  },
  ...
Run Code Online (Sandbox Code Playgroud)
new Chart('canvas', {
  type: 'line',
  data: {
    datasets: [{
      label: 'Temperature',
      data: [
        {"x": 1647281788963, "y": 22.9}, 
        {"x": 1647281994496, "y": 26.9}, 
        {"x": 1647282200029, "y": 21.9}, 
        {"x": 1647282405562, "y": 24.9}, 
        {"x": 1647282611094, "y": 28.9}
      ],               
      backgroundColor: 'transparent',
      borderColor: 'red',
      borderWidth: 2,
      tension: 0.5
    }]
  },
  options: {
    scales: {
      x: {
        type: 'time',
        time: {
          unit: 'minute',
          displayFormats: {
              minute: 'DD T'
          },
          tooltipFormat: 'DD T'
        },
        title: {
          display: true,
          text: 'Date'
        }
      },
      y: {
        title: {
          display: true,
          text: 'value'
        }
      }
    }
  }
});
Run Code Online (Sandbox Code Playgroud)