1

I'm trying to append value labels to the bars of a Crossfilter frequency bar chart in line with this solution, but can't get it to work. The data seems to be being passed through correctly; it does appear in the DOM, but is not visible. Grateful for any tips.

Here's my working jsfiddle.

enter image description here HTML

<span>
  <div id="petchart"></div>
</span>

JS

j = [{'pet': 'Felis catus'}, {'pet': 'Canis lupus familiaris'}, {'pet': 'none'}, 
        {'pet': 'Felis catus'}, {'pet': 'Melopsittacus undulatus'}, 
    {'pet': 'Canis lupus familiaris'}, {'pet': 'Canis lupus familiaris'}];

cf = crossfilter(j);
pets_chart = dc.barChart("#petchart");
petDimension = cf.dimension(function(d) {return d.pet;});
petCountGroup = petDimension.group();

pets_chart
  .dimension(petDimension)
  .group(petCountGroup)
  .x(d3.scale.ordinal().domain(["Felis catus","Canis lupus familiaris","Melopsittacus undulatus","none"])) 
  .xUnits(dc.units.ordinal)

  pets_chart.on("renderlet", function(d){
    pets_chart.selectAll("rect")
        //.selectAll("text").remove()
        .append("g").attr('class', 'selection_total')
        .append("text")
        .data(petCountGroup.all())
        .attr("text", function(d) { console.log(d); return d.value; })
  })

    .width(300).height(250)
  .colors(['#1f77b4']).colorAccessor(function(d, i){ return i; })
  .xAxis().ticks(2);

dc.renderAll();

CSS

g.selection_total text{
  font-size: 1em;
  fill: black;
}
Community
  • 1
  • 1
geotheory
  • 22,624
  • 29
  • 119
  • 196

1 Answers1

0

Updated fiddle here: https://jsfiddle.net/p1j10mgx/7/

The main problem with your former code is that it was putting <text>objects within <rect>s, which is not feasible. Instead, you need to add them under an higher g block, say ".chart-body". Then the main trick is to get the coordinates right.

For the coordinates I used the solution you mentioned (here) and gave the set of <rect> objects as data to the labels. Then you get the coordinates directly from the <rect> object itself, and all additional information you might need is within the object's own .data() field.

Community
  • 1
  • 1
tarulen
  • 2,070
  • 9
  • 14