Chart.js 时间刻度轴显示大数字而不是日期

问题描述 投票:0回答:1

我正在尝试创建一个 google 表格网络应用程序,它将从电子表格中读取数据以生成此图表,这就是我使用 vanilla JS 的原因。

function getEventEntries() {
  function createChart(args) {
    const ctx = document.getElementById("myChart").getContext("2d");
    const cfg = {
      type: 'scatter',
      data: {
        datasets: [{
          label: 'Events',
          data: args
         }],
         options: {
          scales: {
            x: { type: 'time' },
            y: { type: 'linear' }
          }
        }
      }
    };
    
    const myChart = new Chart(ctx, cfg);
  }
  
  //get data from google sheets
  //google.script.run.withSuccessHandler(createChart).getEntries();
  
  // dummy data tests to figure out what formats will work
  var events = [{x: '2021-11-06 23:39:30', y: -3}, {x: '2008-04-12 13:30:14', y: 10}];
  var events1 = [{x: new Date('2021-11-06'), y: -3}, {x: new Date('2008-04-12'), y: 10}]; // actually plots data and creates an x-axis that isn't 0 to 1--still not showing date values for ticks tho
  
  createChart(events1);
}

function onLoad() {
  getEventEntries();
}

$(document).ready(onLoad);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
<!-- I've tried date-fns and moment.js adapters with no luck either -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/global/luxon.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

 <canvas id="myChart"></canvas>

正如您在运行我的代码片段时所看到的,x 轴没有以任何格式列出日期。这只是大数字。我想让它列出可读的日期,也许是 MMM YYYY 格式。

javascript chart.js axis-labels timeline
1个回答
0
投票

假设您正在使用

latest
Chart.js
版本,您将需要传递正确的
configuration
对象,以便它可以根据提供的
dates
渲染
format
。你能试试这样吗:

 const cfg = 
  {
    type: 'scatter',
    data: {
      datasets: [
        {
          labels: "Events",          
          data: args,
        }
      ]
    },
    options: {
      scales: {
        x: [ {
            display: true,
            type: 'time',
            time: {
              parser: 'MM/DD/YYYY HH:mm',
              tooltipFormat: 'll HH:mm',
              unit: 'day',
              unitStepSize: 1,
              displayFormats: {
                'day': 'MM/DD/YYYY'
              }
            }
          }
        ],
        y: [
          // etc...
        ],
      }
    }
  }
);

更新

对于

2.x
的旧版本
Chart.js
,时间刻度需要同时存在
date library and corresponding adapter
。默认情况下,Chart.js 包含
Moment.js
的适配器。更多信息这里.

参考文档:Time Axis Specific Options

希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.