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 . In chart it displays all month for 3 years. But I need to display only for 1 year. Any id
Solution 1:
You can do it by defining the min and max values under the time key.
If
minormaxis 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>
Post a Comment for "Chartjs How To Set Max Labels For X Axis?"