dc.js: 使用图片作为图例

dc.js: use image for the legend

我想使用图像(图标或 svg)代替饼图图例的默认矩形。 是否可以在 dc.js 中执行此操作?

例如:

非常感谢。

此功能不是内置的,但通常很容易 "escape to d3" 并根据需要自定义您的图表。

在这种情况下,我们要等到图表呈现后再用图像替换矩形:

chart.on('pretransition', function(chart) { // 1
   var items = chart.selectAll('.dc-legend .dc-legend-item'); // 2
   items.selectAll('rect').remove(); // 3
   var images = items.selectAll('image').data(function(x) { // 4
       return [x];
   });
   images.enter().append('image').attr({ // 5
       width: 25,
       height: 25,
       href: function(leg) { return _icons[leg.name]; }
   });
   console.log('items', items.data());
});
  1. 等待图表render/redraw
  2. Select 图例项
  3. 删除每个项目下的任何 rect(如果是折线图,您将不得不寻找 line 而不是
  4. Select 任何现有图像(返回单项数组的 "trick" 是为了让我们可以干净地替换那里的任何东西,而不是继续添加更多图像)
  5. 并设置 image - 在这个例子中,我使用了一些我能在 CDN 上找到的第一个 SVG 图标;我们使用对象将堆栈名称映射到 SVG URL。

最后,我们还需要设置图例的项目高度以匹配图像高度:

chart.legend(dc.legend().itemHeight(25));

示例输出:

示例 fiddle:https://jsfiddle.net/gordonwoodhull/Lss5wsz6/9/