Reputation: 3709
I have an X Axis that is currently displaying the number of days based on the range of the data. Because the number of days are so large, it would be helpful to create a custom formatter to show the days in number of years, instead.
Here is my current X Axis and Scale:
var xScale = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d["ttc"]; })])
.range([padding, w-padding])
.nice();
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom')
.ticks(5);
My domain is currently something like [0, 9,000]
days. I want these to display these in years or months. How can I do this?
Upvotes: 0
Views: 126
Reputation: 383
If you are dealing with relative time, where only you know the units, you'll have to write a custom formatter. Maybe something like this will work, but you'll have to figure out how elegant you want your function to be. I wrote a quick "no-thought-added" formatter, but you'll probably want to put some thought into it:
var ...,
max = xRange.domain()[1],
xAxis = d3.svg.axis()
.scale(xRange)
.tickSize(5)
.tickFormat(function (days) {
if (max < 50) {
return d3.format("2.1f")(days) + " d";
}
else if (max >= 50 && max < 100) {
return d3.format("2.1f")(days/7) + " w";
}
else if (max >= 100 && max < 500) {
return d3.format("2.1f")(days/(365/12)) + " m";
}
else if (max >= 500){
return d3.format("2.1f")(days/365) + " y";
}
}
)
here is a simple, ugly, demo to show this: plunker
change the data points to see it switch scales.
Upvotes: 1