Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active December 19, 2016 20:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbostock/9764126 to your computer and use it in GitHub Desktop.
Save mbostock/9764126 to your computer and use it in GitHub Desktop.
Tick Format
license: gpl-3.0

By passing a format specifier to scale.tickFormat, you create a number format with precision appropriate to the scale’s tick values. When a SI-prefix format type is used (type s), the scale also computes a consistent SI-prefix for all ticks, as shown on the left; this feature is new in 3.4.4. In contrast, when d3.format is used directly as shown in the middle, the SI prefix can precision can vary for each tick. In 4.0, you can also create a consistent SI-prefix formatter manually using d3.formatPrefix.

<!DOCTYPE html>
<meta charset="utf-8">
<svg width="960" height="500"></svg>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
margin = {top: 20, right: 0, bottom: 20, left: 0},
width = svg.attr("width") - margin.left - margin.right,
height = svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scalePoint()
.domain([0, 1, 2])
.range([0, width])
.padding(1);
var y = d3.scaleLinear()
.domain([-1e6, 2e6])
.range([height, 0]);
g.append("g")
.attr("transform", "translate(" + x(0) + ",0)")
.attr("class", "axis")
.call(d3.axisLeft(y)
.ticks(20, "s"));
g.append("g")
.attr("transform", "translate(" + x(1) + ",0)")
.attr("class", "axis")
.call(d3.axisLeft(y)
.ticks(20)
.tickFormat(d3.format(".0s")));
g.append("g")
.attr("transform", "translate(" + x(2) + ",0)")
.attr("class", "axis")
.call(d3.axisLeft(y)
.ticks(20)
.tickFormat(d3.formatPrefix(".1", 1e6)));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment