Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the D3.js axis ticks and positions as an array?

Tags:

I usually place my axis ticks on the svg using this:

d3.svg.axis().scale(xScale(width)).ticks(4) 

Is it possible to get these tick values and their svg coordinates so I can use a custom axis outside the svg using d3.svg.axis() ?

like image 280
el_pup_le Avatar asked Mar 28 '14 20:03

el_pup_le


People also ask

What are ticks d3?

d3. ticks generates an array of nicely-rounded numbers inside an interval [start, stop]. The third argument indicates the approximate count of values needed. For example, to cover the extent [0, 10] with about 100 values, d3.ticks will return these ticks: start = 0.

What is d3 js axis component?

Advertisements. D3 provides functions to draw axes. An axis is made of Lines, Ticks and Labels. An axis uses a Scale, so each axis will need to be given a scale to work with.


1 Answers

Yes, xScale.ticks(4) should give you the actual tick points as values, and you can pipe those back through your xScale to the the X position. You can also just pull the tick points back from the generated elements after you apply the axis to an actual element:

var svg = d3.select("svg");  var scale = d3.scale.linear()     .range([20, 280])     .domain([0, 100])  var axis = d3.svg.axis().scale(scale).orient("bottom").ticks(9); // grab the "scale" used by the axis, call .ticks() // passing the value we have for .ticks() console.log("all the points", axis.scale().ticks(axis.ticks()[0])); // note, we actually select 11 points not 9, "closest guess"  // paint the axis and then find its ticks svg.call(axis).selectAll(".tick").each(function(data) {   var tick = d3.select(this);   // pull the transform data out of the tick   var transform = d3.transform(tick.attr("transform")).translate;    // passed in "data" is the value of the tick, transform[0] holds the X value   console.log("each tick", data, transform); }); 

jsbin

like image 105
gnarf Avatar answered Sep 29 '22 23:09

gnarf