1

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

.showLegend(false)

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

4

1 回答 1

6

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

首先使用 class 创建所有元素的选择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

于 2014-06-25T17:11:08.107 回答