Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing size of D3 tick marks based on tick value

I've created a x-axis with a custom tickFormat in D3.

It prints a tick for each month, but labels January as the year, i.e 2014, 2013, etc.

var xAxis = d3.svg.axis()
    .scale(x)
    .orient('bottom')
    .ticks(d3.time.month, 1)
    .tickFormat(d3.time.format.multi([["%b", function(d) { return d.getMonth(); }], ["%Y", function() { return true; }]]))
    .tickSize(4)
    .tickPadding(8);

I'd like to vary the tickSize as well and have a long tick for the year markers.

But it doesn't appear you can use a function to return a value. This should print a random tick size for each date, but fails:

.tickSize(function(d){ return Math.random() * 50 })
like image 481
arm5077 Avatar asked Oct 18 '25 13:10

arm5077


2 Answers

Here's your answer. Custom tick size on axis (d3js)

TLDR: tickSize can only accept numbers, not functions. You need to select them after they are drawn then resize them.

like image 159
Greg Jennings Avatar answered Oct 20 '25 03:10

Greg Jennings


axis.tickSize doesn't accept a function as an argument. It only accepts a scalar value or an array of 2 scaler values (one value for the length of the inner ticks and one for the length of the 2 outer ticks at the end of the domain line).

If you wish to conditionally style ticks you can use post-selection to grab the ticks after they are drawn and either style them directly or set CSS classes to get them to pick up the styles you wish. There is a good example of how to do this here: D3 Axis Tick Post-selection.

like image 31
Scott Cameron Avatar answered Oct 20 '25 04:10

Scott Cameron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!