将X轴标签格式化为Chart.js中的时间值

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

enter image description here使用chart.js,我想将底部图表标签重新格式化为MM DD格式(即2月2日)如何获取chart.js将数据识别为日期并将其转换?它来自我的csv文件:2020-02-06

这是我的chart.js编码,但似乎不起作用。

    data: {
            labels: dollar.years,
            datasets: [
              {label: 'Cdn dollar in cents',
                data: dollar.vals,
                fill: false,
                borderColor: '#4BD0B0',
                pointRadius: 0,
                borderWidth: 8
              }
                      ]
                },

          options: {
          legend:{
          display:false,
          usePointStyle: true,

          labels: {
          boxwidth:10,
          rotation:90
                    }
                  },

          scales: {

          yAxes: [{
          gridLines:{
          display:true
                    },

          ticks: {
          min: .74,
          max: .76,
          stepSize: .025,
                }
                }],

          xAxes: [{
          gridLines:{
          display:true
                },
          ticks: {
          labelOffset: 1,
                },
                  }],
                  }
                  }
        });
      }
javascript chart.js
1个回答
0
投票

您需要将xAxis定义为具有“天”单位的time cartesian axis

[day]的默认display format是'MMM D'(例如'Feb 2')。

options: {
    ...
    scales: {
        xAxes: [{
            type: 'time',
            time: {
                unit: 'day',
                tooltipFormat: 'MMM DD' 
            }
            ...
        }]
    }
    ... 
}

请查看以下可运行的代码段:

new Chart(document.getElementById('myChart'), {
  type: 'line',  
  data: {
    labels: ['2020-02-06', '2020-02-07', '2020-02-08', '2020-02-09', '2020-02-10', '2020-02-11', '2020-02-12'],
    datasets: [{
      label: 'My Dataset',
      data: [0.758, 0.756, 0.755, 0.754, 0.753, 0.758, 0.76],
      fill: false,
      backgroundColor: 'green',
      borderColor: 'green'
    }]
  },
  options: {
    responsive: true,
    title: {
      display: false
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          min: .74,
          max: .76,
          stepSize: .005
        }
      }],
      xAxes: [{
        type: 'time',
        time: {
          unit: 'day',
          tooltipFormat: 'MMM DD'
        }
      }],
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="80"></canvas>
© www.soinside.com 2019 - 2024. All rights reserved.