Skip to content

Instantly share code, notes, and snippets.

@iansinnott
Last active November 1, 2016 18:00
Show Gist options
  • Select an option

  • Save iansinnott/cbf657413e39ac145d7a466851828a5f to your computer and use it in GitHub Desktop.

Select an option

Save iansinnott/cbf657413e39ac145d7a466851828a5f 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.

forked from mbostock's block: Tick Format

<!DOCTYPE html>
<meta charset="utf-8">
<svg width="960" height="500"></svg>
<script src="//d3js.org/d3.v4.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.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, 3])
.range([0, width])
.padding(1);
var y = d3.scaleLinear()
.domain([-1e6, 2e6])
.range([height, 0]);
var t = d3.scaleTime()
.domain([moment().subtract(5, 'months').toDate(), new Date()])
.range([0, height])
.nice();
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)));
g.append('g')
.attr("transform", "translate(" + x(3) + ",0)")
.attr("class", "axis")
.call(d3.axisLeft(t)
.ticks(20)
.tickFormat(d3.timeFormat('%m/%d/%Y')))
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment