Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skipping overlapping labels on x-axis for a barchart in dc.js

Tags:

d3.js

dc.js

How do I skip labels on x axis in dc.js chart dynamically, so that they should not overlap for large dataset.

enter image description here

Here is part of my script

 requestDateBarChart
            .width(725)
            .height(300)
            .margins({top: 10, right: 10, bottom: 60, left: 30})
            .dimension(requestDateDimension)
            .group(requestDateGroup)
            .x(d3.scale.ordinal().domain(coh.map(function (d) {return d.customerRequestDate; })))
            .xUnits(dc.units.ordinal)
            .elasticY(true)
            .renderHorizontalGridLines(true)
            .on('renderlet',function(chart){
                  chart.selectAll("g.x text")
                    .attr('dx', '-15')
                    .attr('transform', "rotate(-55)");
                })
            .controlsUseVisibility(true);
like image 200
ashishraaj Avatar asked Mar 10 '23 12:03

ashishraaj


1 Answers

The axes in dc.js are produced by d3.js, so there's a huge community out there to help with this one. To access the x Axis you can use chart.xAxis() - just be careful because this returns an axis object, so I don't recommend chaining it with your other chart initialization code.

In this case, I searched for "d3 axis ordinal ticks" and this example popped up. The relevant function is axis.tickValues().

Since you're using coh.map(function (d) {return d.customerRequestDate; }) to produce the x scale domain, you could use every 4th tick like so:

var domain = coh.map(function (d) {return d.customerRequestDate; });
requestDateBarChart.x(d3.scale.ordinal().domain(domain))
var ticks = domain.filter(function(v, i) { return i % 4 === 0; });
requestDateBarChart.xAxis().tickValues(ticks);

If you figure out some maximum number of ticks MAXTICKS that can fit in the space, you could maybe do:

var stride = Math.ceil(domain.length / MAXTICKS);
var ticks = domain.filter(function(v, i) { return i % stride === 0; });
like image 176
Gordon Avatar answered May 09 '23 18:05

Gordon