I'm trying to apply d3.time.format("%b-%Y")
to the dates used on the x-axis.
Here is the code which adds the axis and labels
var xLabels = svg
.append("g")
.attr("transform", "translate(" + margin.left + "," + (margin.top + height + 12) + ")");
var formatDateOutputX = d3.time.format("%b-%Y");
xLabels.selectAll("text.xAxis")
.data(BarData)
.enter()
.append("text")
.text(function(d) {
return d.dt; //<< returns dates
//return formatDateOutputX(d.dt); //<< NOTHING RETURNED
})
.attr({
'text-anchor': "middle",
transform: function(d, i) {
var x = (i * (width / BarData.length)) + ((width / BarData.length - barPadding) / 2);
var y = 20;
return 'translate(' + x + ',' + y + ')rotate(-90)';
},
dy: "0.35em", //dx: "-1.05em",
'class': "xAxis"
});
The above relates to the lines of code 285-309 of this visualisation: https://plnkr.co/edit/3d5UhM?p=preview
Hoping someone can help as this will be a fairly common manipulation that I will want to apply. What am I doing wrong?
You are not passing a valid date to formatDateOutputX
so it doesn't know how to process it. You have to parse the value appropriately and you can do it in many ways. Since d3 provides a parse
method to time.format
that is probably the best way to follow.
In your case something like this will work:
var formatDateOutputX = d3.time.format("%b-%Y");
var readDate = d3.time.format("%d/%m/%Y").parse;
xLabels.selectAll("text.xAxis")
.data(BarData)
.enter()
.append("text")
.text(function(d) {
return formatDateOutputX(readDate(d.dt));
})
Check the Plunkr.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments