1π
β
It looks like chartjs is having a tough time getting the bar widths right on a dynamic x scale. A quick method to achieve what you want is to use the normal category scale on the x-axis and format the label at display time. To do that you options
will look something like;
options: {
scales: {
xAxes: [{
ticks: {
userCallback: function(label, index, labels) {
return moment(label, "YYYYMMDD").format("MMM DD, YYYY");
},
},
}],
}
}
The userCallback
function in ticks
just has to return a string so you can format it however you want.
var labels = ["20170601", "20170602", "20170403", "20170503", "20170703", "20170404", "20170504", "20170704", "20170405", "20170505", "20170605", "20170705", "20170406", "20170606", "20170607", "20170608", "20170509", "20170609", "20170510", "20170511", "20170412", "20170512", "20170612", "20170413", "20170613", "20170414", "20170614", "20170515", "20170615", "20170516", "20170616", "20170517", "20170418", "20170518", "20170419", "20170519", "20170619", "20170420", "20170620", "20170421", "20170621", "20170522", "20170622", "20170523", "20170623", "20170424", "20170524", "20170425", "20170426", "20170526", "20170626", "20170427", "20170627", "20170328", "20170428", "20170628", "20170329", "20170529", "20170629", "20170330", "20170530", "20170630", "20170331", "20170531"],
values = [5.79, 7.41, 7.08, 7.25, 7.46, 6.79, 7.01, 5.38, 7.35, 7.4, 7.1, 0.49, 7.57, 5.63, 4.15, 7.32, 5.55, 5, 3.26, 6.78, 2.75, 7.27, 7.33, 5.69, 7.1, 7.28, 6.85, 7.27, 6.4, 6.8, 6.9, 7.19, 3.97, 7.11, 6.89, 6.6, 4.03, 7.11, 5.49, 5.31, 2.43, 6.09, 6.14, 5.4, 3.7, 7.13, 5.72, 5.56, 5.4, 7.18, 7.08, 7.19, 7.39, 5.38, 6.96, 7.16, 5.34, 7.21, 5.98, 7.05, 7.32, 3.23, 6.88, 6.86];
var ctx = document.getElementById("chart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: "Time",
data: values,
}]
},
options: {
scales: {
xAxes: [{
ticks: {
userCallback: function(label, index, labels) {
return moment(label, "YYYYMMDD").format("MMM DD, YYYY");
},
},
}],
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<div id="chart-wrapper">
<canvas id="chart"></canvas>
</div>
Source:stackexchange.com