【问题标题】:Text labels on crossfilter bars do not appear交叉过滤条上的文本标签不显示
【发布时间】:2016-08-04 09:24:11
【问题描述】:

我正在尝试将值标签附加到符合this solution 的 Crossfilter 频率条形图的条形图上,但无法正常工作。数据似乎正在正确传递;它确实出现在 DOM 中,但不可见。感谢任何提示。

这里是my working jsfiddle

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

【问题讨论】:

    标签: d3.js crossfilter


    【解决方案1】:

    在此处更新小提琴:https://jsfiddle.net/p1j10mgx/7/

    您以前的代码的主要问题是它将&lt;text&gt;objects 放在&lt;rect&gt;s 中,这是不可行的。 相反,您需要将它们添加到更高的g 块下,例如".chart-body"。然后主要的技巧是获得正确的坐标。

    对于坐标,我使用了您提到的解决方案 (here),并将 &lt;rect&gt; 对象集作为 data 提供给标签。然后,您可以直接从 &lt;rect&gt; 对象本身获取坐标,您可能需要的所有其他信息都在对象自己的 .data() 字段中。

    【讨论】:

      猜你喜欢
      • 2017-06-05
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多