无法更改图例符号nvd3气泡图

时间:2014-06-25 16:02:54

标签: d3.js legend nvd3.js bubble-chart

在我的nvd3气泡图中,每组点都有不同的符号,但图例全部为圆圈。代码是here。我只碰到过这个

.showLegend(false)

可以隐藏或显示图例。 我无法理解如何更改图例中的符号。

1 个答案:

答案 0 :(得分:6)

nvd3不允许您直接访问图例的内部。但是,您可以使用d3选项相当容易地更改它以操纵其各个部分。

首先创建一个包含类nv-series的所有元素的选择。此类代表图例中的单个组,同时包含圆圈符号和文本(在您的情况下' Group0',' Group1'等)。这将返回一个数组,第一个元素(索引0)是所有元素的数组:

// all `g` elements with class nv-series
d3.selectAll('.nv-series')[0]

接下来,使用Array.forEach()函数迭代此数组,并为每个元素替换圆元素和相应的符号,使填充颜色与已删除的圆匹配。

为了做到这一点,您还需要重复使用之前创建的符号列表,并迭代它们,以便为每个组分配正确的符号。这是实现这一目标的一种方法,但也许您可以想到一种更简单的方法:

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

以下是更新后的JSFiddle


=====编辑=====

我已经经历了nvd3代码库,并且有一种更简单的方法可以在取消激活时触发图例符号以解除填充。它可以简单地定位在你的CSS中,因为该系列在禁用时会被赋予disabled类。

如果添加以下css ...

.nv-series.disabled path {
    fill-opacity: 0;
}

...然后你可以删除所有hacky JavaScript点击处理。它更干净,实际上它们在使用默认的圆形元素时处理它的方式。

这里有更新的JSFiddle