Din*_*esh 1 bubble-chart legend d3.js nvd3.js
在我的nvd3气泡图中,每组点都有不同的符号,但图例全部为圆圈.代码在这里.我只碰到过这个
.showLegend(false)
Run Code Online (Sandbox Code Playgroud)
它可以隐藏或显示图例.我无法理解如何更改图例中的符号.
nvd3不允许您直接访问图例的内部.但是,您可以使用d3选项相当容易地更改它来操纵其各个部分.
首先用类创建所有元素的选择nv-series.此类表示图例中的单个组,同时包含圆圈符号和文本(在您的情况下为"Group0","Group1"等).这将返回一个数组,第一个元素(索引0)是所有元素的数组:
// all `g` elements with class nv-series
d3.selectAll('.nv-series')[0]
Run Code Online (Sandbox Code Playgroud)
接下来,使用该Array.forEach()函数迭代此数组,并为每个元素,用适当的符号替换circle元素,将填充颜色与已删除的圆匹配.
为此,您还需要重复使用之前创建的符号列表,并迭代它们,以便为每个组分配正确的符号.这是实现这一目标的一种方法,尽管您可以想到一种更简单的方法:
// reuse the order of shapes
var shapes = ['circle', 'cross', 'triangle-up', 'triangle-down', 'diamond', 'square'];
// loop through the legend groups
d3.selectAll('.nv-series')[0].forEach(function(d,i) {
// select the individual group element
var group = d3.select(d);
// create another selection for the circle within the group
var circle = group.select('circle');
// grab the color used for the circle
var color = circle.style('fill');
// remove the circle
circle.remove();
// replace the circle with a path
group.append('path')
// match the path data to the appropriate symbol
.attr('d', d3.svg.symbol().type(shapes[i]))
// make sure the fill color matches the original circle
.style('fill', color);
});
Run Code Online (Sandbox Code Playgroud)
这是更新的JSFiddle.
=====编辑=====
我已经经历了nvd3代码库,并且有一种更简单的方法可以在取消激活时触发图例符号以解除填充.它可以简单地定位在你的css中,因为系列被赋予一类disabled禁用时.
如果你添加以下css ...
.nv-series.disabled path {
fill-opacity: 0;
}
Run Code Online (Sandbox Code Playgroud)
...然后你可以删除所有hacky JavaScript点击处理.它更干净,实际上它们在使用默认的圆形元素时处理它的方式.
这是更新的JSFiddle.