NVD3 chart with correctly displayed date labels on the x-axis
Illustration to this answer on Stackoverflow https://stackoverflow.com/a/65256575/1713526
by AlexLukin
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.2/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.6/nv.d3.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.6/nv.d3.min.css">
<div class="graph_content">
<svg id="svg"></svg>
</div>
JavaScript
var shortMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
function getChartData(data) {
var values = data.map(function(val) {
return {
x: val.x.getUTCFullYear() * 12 + val.x.getUTCMonth(),
y: val.y
}
});
return [{
values: values,
key: 'date'
}];
}
function formatDate(numericValue) {
var year = Math.floor(numericValue / 12);
var month = numericValue % 12;
return shortMonthNames[month] + ' ' + year;
}
nv.addGraph(function() {
var data = [
{
x: new Date(2020, 0, 23, 13, 46),
y: 155
},
{
x: new Date(2020, 1, 7, 8, 55),
y: 130
},
{
x: new Date(2020, 2, 15, 15, 12),
y: 90
},
{
x: new Date(2020, 3, 3, 3, 54),
y: 50
},
{
x: new Date(2020, 4, 18, 18, 33),
y: 150
},
{
x: new Date(2020, 5, 28, 23, 5),
y: 200
},
{
x: new Date(2020, 6, 8, 14, 38),
y: 177
},
{
x: new Date(2020, 7, 26, 25, 24),
y: 80
},
{
x: new Date(2020, 8, 25, 4, 12),
y: 35
},
{
x: new Date(2020, 9, 18, 22, 11),
y: 140
},
{
x: new Date(2020, 10, 7, 13, 54),
y: 184
},
{
x: new Date(2020, 11, 5, 15, 41),
y: 133
}
];
var chart2 = nv.models.lineChart()
.options({
transitionDuration: 300,
useInteractiveGuideline: true
})
.showXAxis(true)
.showYAxis(true);
chart2.xAxis.tickFormat(formatDate);
chart2.yAxis.tickFormat(d3.format(',f'));
d3.select('svg#svg')
.datum(getChartData(data))
.call(chart2);
nv.utils.windowResize(chart2.update);
return chart2;
});