ChartJS如何设置X轴的最大标签? [英] ChartJS How to set max labels for X axis?

查看:333
本文介绍了ChartJS如何设置X轴的最大标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个数组接收图表数据,我在那里存储了2016年1月到2018年的日期。在图表中,它显示所有月份为3年。但我只需要显示1年。有什么想法吗?

I receive data for chart from an array , where I stored dates from 2016 , 1 to 2018 , 12 . In chart it displays all month for 3 years. But I need to display only for 1 year. Any ideas?

这里我传递一个数组并更换单位,也是displayFormats

Here i'm passing an array and changing unit for month, also displayFormats

chartHour.config.data.datasets[0].data = array
chartHour.config.options.scales.xAxes[0].time = {
    unit: "month",
    stepSize: 1,
    displayFormats: {
      month: "MMM",
    },
  }


推荐答案

您可以通过定义 min 和<$来实现c $ c> max 时间键下的值。

You can do it by defining the min and max values under the time key.


如果 min max 已定义,则将分别覆盖最小或最大数据。有关详细信息,请参见文档

If min or max is defined, this will override the data minimum or maximum respectively. See docs for more info.



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>

这篇关于ChartJS如何设置X轴的最大标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆