【问题标题】:labels inside the heatmap rects热图矩形内的标签
【发布时间】:2019-07-13 11:59:32
【问题描述】:

我想在框内显示热图框的值,而不仅仅是在工具提示中。

貌似这个功能还没有根据:https://github.com/dc-js/dc.js/issues/1303添加,请问d3.js能做到吗?谢谢。

热图:

        heatMap
            .width(1000)
            .height(400)
            .dimension(dimension)
            .group(filtered_heatMap_group)
            .margins({
                left: 200,
                top: 30,
                right: 10,
                bottom: 50
            })
            .keyAccessor(function (d) {
                return d.key[0];
            })
            .valueAccessor(function (d) {
                return d.key[1];
            })
            .colorAccessor(function (d) {
                return +d.value.color;
            })
            .title(function (d) {
                return "Manager:   " + d.key[1] + "\n" +
                    "FTE:  " + d.value.toolTip + "\n" +
                    "Date: " + d.key[0] + "";
            })
            .rowOrdering(d3.descending);

https://jsfiddle.net/_M_M_/jvf5ot3p/3/

【问题讨论】:

    标签: javascript d3.js dc.js


    【解决方案1】:

    魔鬼在细节中。

    在框上添加一些文本非常容易。让它们很好地定位和格式化将需要更多的工作。无论如何,我会尽力让你开始。

    您可以使用renderlet 事件。 pretransition 会更好,但我们需要从 rects 中窃取一些属性,因为无法访问图表的刻度,并且这些属性并非全部在 pretransition 时间初始化。

    这是 dc.js 中注释的常见模式:等待图表事件,然后选择现有元素并向它们添加内容。元素选择器是documented here;我们想要g.box-group

    其余的是标准的 D3 通用更新模式,除了我提到的,我们无权使用秤。我们可以从已经存在于这些rects 中的rects 中读取xywidthheight 之类的属性,而不是尝试复制该语言并可能弄错。

    SVG 没有多行文本,因此我们必须在 text 元素内创建 tspan 元素。

    综合起来:

      .on('renderlet.label', function(chart) {
            var text = chart.selectAll('g.box-group')
            .selectAll('text.annotate').data(d => [d]);
        text.exit().remove();
        // enter attributes => anything that won't change
        var textEnter = text.enter()
          .append('text')
          .attr('class', 'annotate')
        textEnter.selectAll('tspan')
          .data(d => [d.key[1], d.value.toolTip, d.key[0]])
          .enter().append('tspan')
          .attr('text-anchor', 'middle')
          .attr('dy', 10);
        text = textEnter.merge(text);
        // update attributes => position and text
        text
          .attr('y', function() {
            var rect = d3.select(this.parentNode).select('rect');
            return +rect.attr('y') + rect.attr('height')/2 - 15;
          });
        text.selectAll('tspan')
          .attr('x', function() {
            var rect = d3.select(this.parentNode.parentNode).select('rect');
            return +rect.attr('x') + rect.attr('width')/2;
          })
          .text(d => d);
      })
    

    请注意,我放弃并将文本向上推了 15 像素...可能有也可能没有更好的方法来使多行文本垂直居中。

    文字不太合适,即使没有描述。我会让你弄清楚的。

    但它就在那里,并且可以正确更新:

    Fork of your fiddle.

    【讨论】:

      猜你喜欢
      • 2011-11-20
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      • 2021-01-14
      • 1970-01-01
      • 2016-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多