Reputation: 1085
I am making a choropleth map. When the user hovers over a polygon a simple line graph will be displayed reflecting data contained in that specific polygon.
The data contains a large degree of variation. Some times the domain on the Y axis will be maximum of $400,000,000. In these cases I want to display the figure as "400M." Thats easy enough!
But in some cases the data for a particular polygon might have a maximum value of $100,000 in those cases I would like to display "100K"
In some cases the data may only have a maximum value of $100....
How can I dynamically change the tick format to reflect the different domains that will be encountered?
Upvotes: 2
Views: 853
Reputation: 102174
It seems to me that all you need is to set the ticks to use SI:
.tickFormat(d3.format(".0s"));
Here is a demo:
var svg = d3.select("body").append("svg");
var xScale = d3.scaleLinear()
.range([10, 280]);
var xAxis = d3.axisBottom(xScale.domain([0, 100000000]))
.tickFormat(d3.format(".2s"));
var gX = svg.append("g")
.attr("transform", "translate(0,30)")
.call(xAxis);
<script src="https://d3js.org/d3.v4.min.js"></script>
You can see how this format works for several different values:
var format = d3.format(".2s");
console.log(format(10000000000))
console.log(format(100000000))
console.log(format(4786))
console.log(format(42))
<script src="https://d3js.org/d3.v4.min.js"></script>
Upvotes: 1