Marcel Schürmann
Marcel Schürmann

Reputation: 395

DC.js, crossfilter - dynamic chart height when hiding 0-value-bins / groups

I would like to dynamically set the height of a DC-chart, which contains hidden bins.

It is possible to hide zero-value-bins in a DC-chart with remove_empty_bins() function - see following Post: How can hide dc.js row chart values if values equal zero

I created a group "SubCategoryGroup_nonEmpty", which only contains non-empty bins. But now my chart-height does not adapt to the count of non-empty bins.

I tried to set the .height() with following code:

SubcategoryRowChart
    .dimension(SubCategoryDim)
    .group(SubCategoryGroup_nonEmpty)
    .elasticX(true)
    .valueAccessor(function(p) { return p.value.count > 0 ? p.value.total / p.value.count : 0; })
    ...
    .height(function(anchor) {
        // calculate the height depending on the count of not-hidden bins
        return SubCategoryDim.group().size() * 40; // 40 = size of single element including padding
     });

But with SubCategoryDim.group().size() i only get the total bins but not the filtered ones:

How can I get the count of filtered bins?

Upvotes: 1

Views: 76

Answers (1)

Marcel Schürmann
Marcel Schürmann

Reputation: 395

Gordon - You are my savior! Thanks a lot! :)

Here my final solution:

  • use nonEmptyGroup.all().length to get the filtered count of bins
  • Create the function CalcRowChartHeight_bySingleRowHeight() to calculate row height based on number of bins, row height and margins
    function CalcRowChartHeight_bySingleRowHeight(chart, group, SingleRowHeight){
        var ChartHeight = group.all().length * SingleRowHeight;
        var ChartMargins = chart.margins().top + chart.margins().bottom;
        var Height = ChartHeight + ChartMargins
        return Height;
    }
  • Overwrite the redraw() function which sets the height. The _redraw() function is a copy of redraw(). I used it because I did not figure out how to use the preRedraw event in this case. Any idea?
SubCategoryRowChart
    .dimension(SubCategoryDim)
    .group(SubCategoryGroup_nonEmpty)
    .elasticX(true)
    ...
    .redraw = function (){
        // calculate the height based on the count of non-hidden bins
        SubCategoryRowChart.height(CalcRowChartHeight_bySingleRowHeight(SubCategoryRowChart, SubCategoryGroup_nonEmpty, 40))
        return SubCategoryRowChart._redraw();
    }
    ;

Upvotes: 1

Related Questions