user1340852
user1340852

Reputation: 875

copying data to an array in javascript d3.js and then drawing a scatterplot

Im new to javascript and d3.js and trying to understand scatter plots. I used this code, works fine:

//Get the data
d3.tsv("graphdata.tsv", function (error, data) {
        data.forEach(function (d) {
            d.date = parseDate(d.date);
            d.close = +d.close;
            d.open = +d.open;
        });

x.domain(d3.extent(data, function (d) { return d.date; }));
y.domain([0, d3.max(data, function (d) { return d.close; })]);

// draw the scatterplot
        svg.selectAll("dot")                                    
            .data(data)                                         
        .enter().append("circle")                               
            .attr("r", 8)                                     
            .attr("cx", function (d) { return x(d.date); })     
            .attr("cy", function (d) { return y(d.close); })    
            .style("fill", color(9));

But when I copy the contents of "data" to "anArray", and then try to plot the data in anArray, I get an empty graph.

//Get the data
d3.tsv("graphdata.tsv", function (error, data) {
        data.forEach(function (d) {
            d.date = parseDate(d.date);
            d.close = +d.close;
            d.open = +d.open;
        });

var anArray = new Array();
for (var i = 0; i < 26; i++)
       anArray.push(data[i]);

x.domain(d3.extent(anArray, function (d) { return anArray.date; }));
y.domain([0, d3.max(anArray, function (d) { return anArray.close; })]);

// draw the scatterplot
        svg.selectAll("dot")                                    
            .data(anArray)                                          
        .enter().append("circle")                               
            .attr("r", 8)                                     
            .attr("cx", function (d) { return x(anArray.date); })       
            .attr("cy", function (d) { return y(anArray.close); })  
            .style("fill", color(9));

I want to know why does this happen? And if I need to do such a thing, is there a another way to do it?

Upvotes: 0

Views: 814

Answers (1)

nebulae
nebulae

Reputation: 2665

been a while since I used d3, but I think the problem is here:

x.domain(d3.extent(anArray, function (d) { return anArray.date; }));

y.domain([0, d3.max(anArray, function (d) { return anArray.close; })]);

and

.attr("cx", function (d) { return x(anArray.date); })

.attr("cy", function (d) { return y(anArray.close); })

you're asking it to return anArray.date and anArray.close when it should be d.date and d.close.

try changing this to:

x.domain(d3.extent(anArray, function (d) { return d.date; }));

and

.attr("cx", function (d) { return x(d.date); })

Upvotes: 1

Related Questions