简体   繁体   中英

dc.js / d3.js - How to hide a bar chart x-axis category value if its bar value equals zero?

I know this question has been asked before, but I have not found an answer that works for me.

I looked into https://github.com/dc-js/dc.js/wiki/FAQ#filter-the-data-before-its-charted and tried the remove_empty_bins function but nothing changed. I also tried the filter_bins function but I am getting the error message "f is not a function".

I am working on a dashboard. I want the bar charts to update such that the x-axis categories are removed from the graph when they are zero and will reappear when they are not. The graphs are updated when selecting/unselecting elements in other graphs.

Basically, I don't want my 20+ categories x-axis to show all of them when only 3 (for example) have values when another graph has an element selected. I would like only those 3 (for example) to be shown. I don't want to update the data in a way that I cannot undo the changes since I want to be able to unselect the element from before and have the graph return to its previous state.

In other words, when a bar chart is updated, it should only show the bars with values greater than 0.

Is there an example somewhere that shows how to do this? I have not been able to find one.

This is the code that is getting the error message:

var ndx = crossfilter(data);
var bar = dc.barChart("#bar");
var bar_dim = ndx.dimension(function(d) {return d.name;});
var bar_group = bar_dim.group().reduceSum(function(d) {return +d.count;});
var bar_Fgroup = filter_bins(bar_group);
bar.width(650).height(310)
    .dimension(bar_dim)
    .group(bar_Fgroup)
    .renderHorizontalGridLines(true)
    .gap(2)
    .x(d3.scale.ordinal())
    .xUnits(dc.units.ordinal)
    .elasticY(true)
    .yAxisLabel("count")
    .margins({top:10,left:60,right:10,bottom:110});

bar.on("renderlet",function(_chart){
    _chart.selectAll("g.x text").style("text-anchor","end")
          .attr('dx', '-15').attr('dy', '-2').attr('transform', "rotate(-75)");
    _chart.selectAll("rect.bar").on("click", _chart.onClick);
});

I guess you were probably missing elasticX :

.elasticX(true)

which is not entirely obvious, except if you think of it forcing an update of the X domain each time the filters update.

I've added an example here: http://dc-js.github.io/dc.js/examples/filtering-removing.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM