首页 > 解决方案 > 有没有办法在 Chart.js 中显示没有数据的图表标签

问题描述

我正在尝试在 chart.js 上显示年度失业统计数据,但我没有所有月份的数据。是否可以显示我拥有的所有数据但保留所有标签(例如,我没有 7 月的数据,我希望将标签“7 月”写在那里但图表中没有点)。

标签: javascriptchart.js

解决方案


首先,您应该将 定义xAxis时间笛卡尔坐标轴。然后,您通过包含和属性的对象data将数据集定义为单个点。xy

请注意,Chart.js 在内部使用Moment.js来实现时间轴的功能。因此,您应该使用在单个文件中包含 Moment.js 的 Chart.js捆绑版本。

new Chart(document.getElementById("myChart"), {
  type: "line",
  data: {   
    datasets: [{
      label: "Unemployments",
      data: [
        { x: '2020-01', y: 50 },
        { x: '2020-02', y: 55 },
        { x: '2020-03', y: 67 },
        { x: '2020-04', y: 40 },
        { x: '2020-05', y: 20 },
        { x: '2020-07', y: 35 },
        { x: '2020-08', y: 38 },
        { x: '2020-09', y: 45 },
        { x: '2020-10', y: 48 },
        { x: '2020-11', y: 52 },
        { x: '2020-12', y: 55 }
      ],
      backgroundColor: 'lightblue',
      borderColor: 'blue',
      pointRadius: 5,
      pointHoverRadius: 10,
      fill: false,
    }]
  },
  options: {
    responsive: true,
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }        
      }],
      xAxes: [{
        type: 'time',               
        time: {
          unit: 'month',
          parser: 'YYYY-MM',
          displayFormats: {
            month: 'MMMM'
          },
          tooltipFormat: 'MMMM'
        }
      }]
    },
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>


推荐阅读