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

问题描述 投票:1回答:1

enter image description here

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

例如:

enter image description here

非常感谢。

dc.js
1个回答
2
投票

此功能不是内置的,但通常很容易“逃到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. 等待图表渲染/重绘
  2. 选择图例项
  3. 删除每个项目下的任何rect(如果它是折线图,你将不得不寻找line
  4. 选择任何现有图像(返回单项数组的“技巧”是这样我们可以干净地替换那里的任何东西,而不是继续添加更多图像)
  5. 并设置image - 在这个例子中我使用了一些我可以在CDN上找到的第一个SVG图标;我们使用对象将堆栈名称映射到SVG URL。

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

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

示例输出:

screenshot of legend with icons

示例小提琴:https://jsfiddle.net/gordonwoodhull/Lss5wsz6/9/

© www.soinside.com 2019 - 2024. All rights reserved.