[英]ChartJS How to set max labels for X axis?
I receive data for chart from an array , where I stored dates from 2016 , 1 to 2018 , 12 . 我从一个数组接收图表数据,我在那里存储了2016年1月到2018年的日期。 In chart it displays all month for 3 years.
在图表中,它显示所有月份为3年。 But I need to display only for 1 year.
但我只需要显示1年。 Any ideas?
有任何想法吗?
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",
},
}
You can do it by defining the min
and max
values under the time
key. 您可以通过在
time
键下定义min
和max
。
If
min
ormax
is defined, this will override the data minimum or maximum respectively.如果定义了
min
或max
,则将分别覆盖数据最小值或最大值。 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.