Reputation: 59
I've accessed an API and stored the data in two arrays. Now I'm trying to plot the data from the arrays on a graph in D3.js.
//Read the data
d3.json(BASE_URL).get(function(data) {
console.log(data)
var data = data["near_earth_objects"]
console.log(data)
var today = [];
var neo = [];
var diameter = [];
var distance = [];
for (today of data["2020-01-09"]) {
console.log(today)
diameter.push(Math.round(today["estimated_diameter"]["feet"]["estimated_diameter_max"]))
for (approach of today["close_approach_data"]){
console.log(approach)
distance.push(Math.round(approach["miss_distance"]["lunar"]))
}
}
console.log(diameter)
console.log(distance)
What will be X and Y are the arrays "diameter" and "distance."
.selectAll("dot")
.data(data)
.enter()
.append("circle")
.attr("cx", function (d) { return x(d.distance); } )
.attr("cy", function (d) { return y(d.diamter); } )
.attr("r", 1.5)
.style("fill", "#69b3a2")
I tried plugging in the variables at cx and cy but it didn't work! I was able to plot the points if I read from a csv file but I am now reading from json.
Very new at programming so any help would be greatly appreciated!
Here is what my console.logs are putting out. The two arrays are at the bottom.
Upvotes: 1
Views: 594
Reputation: 1054
There are two mistakes:
When you draw circles you asume that data
object is an array with elements which contains "diameter" and "distance" properties:
svg.append('g')
.selectAll("dot")
.data(data)
.enter()
.append("circle")
.attr("cx", function (d) { return x(d.distance); } )
.attr("cy", function (d) { return y(d.diamter); } )
but in fact you use your initial data
object which have complex structure.
So, you should add something like this:
data2 = diameter.map(function(e,i){return {'diameter': e, 'distance':distance[i]}})
and change your circle rendering to data2:
svg.append('g')
.selectAll("dot")
.data(data2)
.enter()
.append("circle")
.attr("cx", function (d) { return x(d.distance); } )
.attr("cy", function (d) { return y(d.diameter); } )
.attr("r", 3.5)
.style("fill", "#69b3a2")
And second mistake is "diamter" instead of "diameter" in .attr("cy", function (d) { return y(d.diamter); }
Upvotes: 1