【发布时间】:2014-08-16 07:17:21
【问题描述】:
【问题讨论】:
-
没有直截了当的方法,您可能需要调整您的
nvd3.js源文件才能做到这一点。 -
@shabeer90 你能帮忙具体修改什么吗?
标签: d3.js legend nvd3.js bubble-chart
【问题讨论】:
nvd3.js 源文件才能做到这一点。
标签: d3.js legend nvd3.js bubble-chart
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。
【讨论】:
.on('click') 处理程序已被用于触发图形更改,您可以使用.on('mouseup') 检查组是否处于活动状态并删除符号的填充。我意识到这有点 hacky,但目前没有办法解决......您应该向他们的 github 页面提交问题,并让他们知道您希望能够使用合理的 API 自定义图例。这是一个更新后的JSFiddle。
.attr('r', 10) 使图例符号更大,但大小没有改变。
path 元素,因此它们没有半径属性,但您可以使用变换来调整它们的大小和位置。如果您设置.attr('transform', 'scale(1.5)'),则符号将大 1.5 倍。玩弄它,直到你得到适合你的东西。这是更新后的JSFiddle。