在线形图中动态绘制多条线
我想根据此示例创建多折线图表,并需要基于用户选择动态绘制多条线。代码使用以下方法创建行:
I am trying to create a multi-line chart upon this example, and need to draw multiple lines dynamically based on user selections. The code uses following approach to create the lines:
var valueline = d3.svg.line()
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y(d.primary);
});
然后创建 valueline()
以创建路径:
svg.append("path")
.attr("class", "line")
.attr("d", valueline(data));
我使用JSON渲染图表,并有一个简单的对象与键 - 值对数组:
I am using JSON to render the charts and have a simple array of Objects with key-value pairs:
data = [{
"date": "1-Apr-11",
"primary": 58.13,
"secondary": 28.13
}, {
"date": "1-May-11",
"primary": 53.98,
"secondary": 35.13
}];
当前代码只能绘制 primary
。任何人都可以建议一个动态的方式来绘制多行?我试图创建第二个 valueline2()
函数创建第二行,然后另一个 svg.append(path)
用 valueline2()
创建路径。所以行数越多,代码越复杂,所以我不认为这是一个更好的方法。请帮助,真的坚持这一点。
The current code is only able to plot the primary
line. Can anyone please suggest a dynamic way to draw multiple lines? I tried to create a second valueline2()
function to create the second line, and then another svg.append("path")
with line valueline2()
to create the path. So the more the lines, the more duplicate code will be there, so I don't think that's a preferable approach. Please help, really stuck with this.
是的,你不应该创建重复。注意,你的示例中的 valueline
是接受 data
并生成行路径的函数(此函数也称为行生成器)。您可以创建一个函数,它将为每个数据列返回不同的函数(行生成器):
Yes, you should not creating duplicates. Note that valueline
from your example is function which accepts data
and generates line path (this function is also called line generator in API). You can create a function which will return a different function (line generator) per each of your data columns:
// Define the parametric line generator
var valueline = function(field) {
return d3.svg.line()
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y(d[field]);
});
};
...
for (let field of ["primary", "secondary"])
{
// Add the valueline path.
svg.append("path")
.attr("class", "line")
// here you constructing specific line generator and pass data to it
.attr("d", valueline(field)(data));
}
这里的工作示例: https://jsfiddle.net/sdnyn8uf/18/ (抱歉,第二个细分没有可悬停的点)
Working example here: https://jsfiddle.net/sdnyn8uf/18/ (sorry, no hoverable points there for the second segment)