【发布时间】:2017-06-09 03:12:23
【问题描述】:
我被要求在我的多折线图中添加一个交互式图例。我的多线图有一个带有两个键的巢,这让我的传奇变得困难。这是我用来添加交互式图例的旧 EAMPLE。
我的问题:
1) 我正在尝试显示图例的顶级键,以便它显示 system01、system02、system03 等等,而不是同时显示这两个键。例如,system01 0 和 systmem01 2 变为 system01,所以当它被点击时,它会隐藏这两行。
2) 使线条处于非活动状态后,鼠标悬停在图表上时仍会显示工具提示。
这是我的FIDDLE
用于添加图例的代码段:
var chartBody = svg.append("g")
.attr("class", "chartbody")
.attr("clip-path", "url(#clip)");
for (var key in storages) {
if (storages.hasOwnProperty(key)) {
console.log("key:", key, [storages[key]]);
var capSeries = d3.line()
.x(function(d) {
return x(d.date); })
.y(function(d) {
return y(d.availableVolumeCapacity); })
.curve(d3.curveCardinal);
// mapping of data to line using the capSeries function
chartBody.append("path")
.data([storages[key]])
.attr("class", "line")
.attr("id", 'tag'+ key.replace(/\s+/g, ''))
.attr("d", capSeries)
.style("stroke", z(key));
}
}
// spacing for the legend
legendSpace = width/nest.length;
// Loop through each symbol / key
nest.forEach(function(d,i) {
// Add the Legend
svg.append("text")
.attr("x", (legendSpace/2)+i*legendSpace) // space legend
.attr("y", height + (margin.bottom/2)+ 5)
.attr("class", "legend") // style the legend
.style("fill", function() { // Add the colours dynamically
return d.z = z(d.key); })
.on("click", function(){
// Determine if current line is visible
var active = d.active ? false : true,
newOpacity = active ? 0 : 1;
// Hide or show the elements based on the ID
d3.select("#tag"+d.key.replace(/\s+/g, ''))
.transition().duration(100)
.style("opacity", newOpacity);
// Update whether or not the elements are active
d.active = active;
})
.text(d.key);
});
【问题讨论】:
-
我已经解决了你的问题 2,不明白问题 1,看看这个link
-
我很抱歉没有清楚地解释自己。我正在寻找对图例的子键进行分组。例如
system01 0和systmem01 2变成system01所以当它被点击时它会隐藏这两行。 -
@Clarkus978 您可以更改显示的文本,它会正常工作,看看我的回答
-
@mkaran 感谢您的回答,但这并不能解决问题。我希望将
system01 0和system01 02分组,以便在图例中只显示一个system01。当点击system01时,它将隐藏行system01 0和system01 2。 -
@Clarkus978 哦,我明白了!感谢您的澄清
标签: javascript d3.js