简体   繁体   中英

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:

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 ). 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. This is what worked for me. For the paths I didn't need to svg.selectAll anything. line1 and line2 get the data from data variables:

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.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. Hopefully this helps someone who might run into similar issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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