javascript 从 d3.js 中的折线图中删除线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21490020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove line from line graph in d3.js
提问by void
I have a button that displays a line graph using d3.js. But I want to remove the line from the graph on clicking the same button. I have created a toggle button, but how do i remove the line from the graph ? I have the following function that plots the graph. svg.selectAll("path").remove() is removing the axis and but not the line.
我有一个使用 d3.js 显示折线图的按钮。但我想在单击同一按钮时从图表中删除该线。我创建了一个切换按钮,但如何从图表中删除该线?我有以下绘制图形的函数。svg.selectAll("path").remove() 正在移除轴而不是线。
function plotGraph(file) {
函数 plotGraph(file) {
var color = d3.scale.category10();
var svg = d3.select('#mySvg');
svg.selectAll("path").remove();
var line = d3.svg.line().interpolate("basis").x(function(d) {
return x(d.date);
}).y(function(d) {
return y(d.mvalue);
});
d3.csv(file,function(error, data) {
color.domain(d3.keys(data[0]).filter(function(key) {
return key !== "date";
}));
data = data.map(function(d) {
return {
mvalue : +d.mvalue,
date : parseDate(d.date)
};
});
x.domain(d3.extent(data, function(d) {
return d.date;
}));
y.domain([ 0, 100 ]);
svg.append("path").datum(data).attr("class", "line").attr("d",line);
});
}
}
回答by Lars Kotthoff
You have a few options to select a specific element you want to remove. If that element is identified by a class, you can do
您有几个选项可以选择要删除的特定元素。如果该元素由类标识,则可以执行
d3.select("path.line").remove();
If you want to remove all lines on the graph, you should use
如果要删除图形上的所有线条,则应使用
d3.selectAll("path.line").remove();
If, as in your example, there are several of these elements, you can assign an ID to them and use that to remove it.
如果像您的示例一样,有多个这样的元素,您可以为它们分配一个 ID 并使用它来删除它。
svg.append("path")
// ...
.attr("id", "id");
// ...
d3.select("#id").remove();
回答by ckersch
You can store the line in a variable and then use that as a handle to remove it later.
您可以将该行存储在一个变量中,然后将其用作句柄以稍后将其删除。
In d3, the .append
operator returns the appended child, so to do this, all you need to do is this:
在 d3 中,.append
操作符返回附加的孩子,所以要做到这一点,你需要做的就是:
var myLine;
function(appendLine){
...
myLine = svg.append("path").datum(data)...
...
}
function(removeLine){
myLine.remove()
}
Use appendLine
when you want to create the line and removeLine
to remove it. With this method, you can have a variable for each line you want to control, or else use variable scoping to not have to worry about it. It depends on what the rest of your code looks like.
使用appendLine
时要创建的行,removeLine
将其删除。使用此方法,您可以为要控制的每一行设置一个变量,否则使用变量范围就不必担心。这取决于您的代码的其余部分是什么样的。
Alternately, if you have a line with an ID that you want to remove, d3.select('#myId').remove()
should work.
或者,如果您要删除带有 ID 的行,则d3.select('#myId').remove()
应该可以使用。