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

感情迁移 提交于 2020-01-15 02:32:37

问题


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);
});

回答1:


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



来源:https://stackoverflow.com/questions/33042138/dc-js-d3-js-how-to-hide-a-bar-chart-x-axis-category-value-if-its-bar-value-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!