简体   繁体   English

如何使用d3将多个变量的数据输入到一张图表中?

[英]How to enter data from several variables into one chart using d3?

It is quite easy to enter data in d3 as long as all of the data are in one file or in one variable like this: 只要所有数据都在一个文件或一个这样的变量中,就可以很容易地在d3中输入数据:

svg.selectAll("path").data(datavariable).enter()
    .append("path")
    ....

I need to enter data stored in separate variables into one graph. 我需要将存储在单独变量中的数据输入到一张图中。 I tried 我试过了

svg.selectAll("path").data(datavariable1).enter()
    .append("path")
    ....
 svg.selectAll("path").data(datavariable2).enter()
    .append("path")
    ....

It doesn't seem to work. 它似乎不起作用。 I also tried svg.selectAll("path1")... and svg.selectAll("path.datavariable1")... , but it just plots the second path over the first using the same data ( datavariable1 ). 我还尝试了svg.selectAll("path1")...svg.selectAll("path.datavariable1")... ,但它只是使用相同的数据( datavariable1 )在第二条路径上绘制了第二条路径。 Does anyone know how to get data from two variables to work on one graph at the same time? 有谁知道如何从两个变量中获取数据以同时处理一张图?

I figured it out with the help of Nixie's comment. 我借助Nixie的评论弄清楚了。 This is what worked for me. 这对我有用。 For the paths I didn't need to svg.selectAll anything. 对于路径,我不需要svg.selectAll任何东西。 line1 and line2 get the data from data variables: line1line2从数据变量获取数据:

var line1 = d3.line()
    .x(function(d,i) { return x(datavariable1[i].xvalue); })
    .y(function(d,i) { return y(datavariable1[i].yvalue); });

var line2 = d3.line()
    .x(function(d,i) { return x(datavariable2[i].xvalue); })
    .y(function(d,i) { return y(datavariable2[i].yvalue); });

Then I just appended SVG as follows: 然后我将SVG附加如下:

svg.append("path")
    .attr("class", "line")
    .attr("d", line1(datavariable1))


svg.append("path")
    .attr("class", "line")
    .attr("d", line2(datavariable2))

Answer in Nixie's comment to my question wouldn't work in my case because path has to stay path for the line graph, but it works for a dot graph. 在Nixie的评论中,对我的问题的回答在我的情况下不起作用,因为path必须保持折线图的path ,但对点图有效。 Hopefully this helps someone who might run into similar issue. 希望这对可能遇到类似问题的人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM