Display Date as range on Axis X - CanvasJS JavaScript Charts
Display Date as range on Axis X - CanvasJS JavaScript Charts
by canvasjs
HTML
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
JavaScript
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
theme: "light2", // "light1", "light2", "dark1", "dark2"
animationEnabled: true,
title: {
text: "Temperature graph"
},
axisY: {
title: "temperature",
gridThickness: 0,
includeZero: true,
maximum:35,
minimum: 8,
},
axisX: {
labelWrap: true,
labelMaxWidth: 50,
labelAngle: 180,
includeZero: true,
gridThickness: 0,
minimum:new Date(2018,11,31),
maximum:new Date(2019,01,03),
valueFormatString: "DD MMM YYYY",
labelFormatter: function(e) {
return customLabel(e.value);
},
},
data: [{
type: "rangeColumn",
indexLabel: "{y[#index]}",
xValueFormatString: "DD MMM YYYY",
toolTipContent: "{x}<br>High: {y[0]}<br>Low: {y[1]}",
dataPoints: [
{
"x":new Date(2019,0,08),
"y":[14,17]
},
{
"x":new Date(2019,0,26),
"y":[15,21]
},
]
}]
});
chart.render();
function customLabel(value) {
var curr = new Date(value); // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = CanvasJS.formatDate( curr.setDate(first), "DD MMM");//Use formatDate function to format the date based on your requirement
var lastday = CanvasJS.formatDate( curr.setDate(last), "DD MMM");//Use formatDate function to format the date based on your requirement
return firstday + '-' + lastday;
//return firstday ;
}
}