Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.js alternative to axis.tickSubdivide?

Tags:

d3.js

I want to draw subtick in the axis in D3. But it seems impossible in the latest D3.

There was axis.tickSubdivide() function to draw the subtick, but I think that is deprecated.(https://github.com/mbostock/d3/commit/bd0ce6cab8a2b0d2aaffc7ce21a873fc514eb8ed)

And axis.tickSubdivide() is not on the API(https://github.com/mbostock/d3/wiki/API-Reference) any more.

I tried with axis.innerTickSize but it didn't work.

Is there any way to draw subtick on the axis at my disposal?

I found an example(http://bl.ocks.org/GerHobbelt/3605124) which used axis.tickSubdivide(), but I can't figure out how it can work even when embedded d3.v3.min.js says "n.tickSubdivide=function(){return arguments.length&&n}", which doesn't do anything and just return the axis.

like image 871
hanmomhanda Avatar asked Feb 08 '14 08:02

hanmomhanda


2 Answers

The new way to do this is to have several axes, one for the major ticks and another one for the minor ones. You would select the ticks that also appear on the major axis for the minor one and remove them:

svg.append("g")
  .attr("class", "grid")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.svg.axis().scale(x).ticks(20).tickSize(-height))
  .selectAll(".tick")
  .data(x.ticks(10), function(d) { return d; })
  .exit()
  .classed("minor", true);

svg.append("g")
  .attr("class", "axis")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.svg.axis().scale(x).ticks(10));

Complete example here.

like image 119
Lars Kotthoff Avatar answered Sep 20 '22 01:09

Lars Kotthoff


An alternative to drawing two axes is to draw all the ticks initially, then re-select them and adjust their styles according to their data or index values.

Example and more explanation here:
https://stackoverflow.com/a/21583985/3128209

There are a few benefits to this approach:

  • you can make multiple levels of tick styles, not just major/minor, without adding additional complication to the code
  • your DOM ends up cleaner, with only one axis group and only one set of tick labels

However, the one thing you couldn't do easily is to have both an axis with tick marks and a grid across the plotting area, as in Lars' sample code.

like image 25
AmeliaBR Avatar answered Sep 20 '22 01:09

AmeliaBR