ChartJS如何设置X轴的最大标签数?

3
我从一个数组中收到图表数据,其中我存储了从2016年1月到2018年12月的日期。在图表中,它显示了三年的所有月份。但是我只需要显示一年的。有什么想法吗?
这里我传递一个数组并更改月份的单位,同时显示格式。
chartHour.config.data.datasets[0].data = array
chartHour.config.options.scales.xAxes[0].time = {
    unit: "month",
    stepSize: 1,
    displayFormats: {
      month: "MMM",
    },
  }

在图表中,它显示了三年的所有月份。但我只需要显示一年的数据。您是指最多显示2016-2018年的12个条目,还是仅显示特定年份(如仅显示2017年)的每月数据? - Ana Liza Pandac
@AnaLizaPandac 只针对特定年份,比如2017! - Yerlan Yeszhanov
1个回答

1
你可以通过在 time 键下定义 minmax 值来实现。

如果定义了 minmax,这将覆盖数据的最小值或最大值。有关更多信息,请参见 文档

chartHour.config.options.scales.xAxes[0] = {
  type: "time",
  time: {
    min: "2017-01-01",
    max: "2017-12-01",
    displayFormats: {
      day: "MMM YY"
    }
  }
};

See working example below.

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const years = [2016, 2017, 2018];

const labels = [];
const dataSet = [];
years.forEach((year, index) => {
  months.forEach((month, monthIndex) => {
    const date = moment(`${month} ${year}`, "MMM YYYY").format('YYYY-MM-DD');
    labels.push(date);
    dataSet.push({
      x: date,
      y: (monthIndex + 12) * (index + 1)
    });
  });
});

var data = {
  labels: labels,
  datasets: [{
    pointRadius: 0,
    label: "Positive",
    lineTension: 0,
    data: dataSet,
    borderWidth: 1,
    backgroundColor: "rgba(0, 255, 0, 0.5)"
  }]
};
var options = {
  scales: {
    xAxes: [{
      type: "time",
      distribution: 'series',
      time: {
        min: "2017-01-01",
        max: "2017-12-01",
        displayFormats: {
          day: 'MMM YY'
        }
      },
      ticks: {
        source: "labels"
      },
      gridLines: {
        display: false
      }
    }]
  }
};

var ctx = document.getElementById("myChart").getContext("2d");

var myBarChart = new Chart(ctx, {
  type: "bar",
  data: data,
  options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<canvas id="myChart" width="300" height="100"></canvas>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接