I am trying to dynamically add graphs to my webpage using for loop. Each graph in a separate row of a table. But only the last graph is being displayed. For others, the g element is not getting added.
This is the hierarchy of last graph(Successful one) :- tr -> td -> svg -> g(transform) -> g(x axis) -> g(y axis) -> path
and for the other, it is :- tr -> td -> svg -> g(transform)
On further analysis, I found that in the successful graph, path, x and y axis are added as many number of times, as the loop is running.
here is my code :-
// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d[xA]); })
.y(function(d) { return y(d[yA]); });
for(var i = 0; i < yAV.length; i++){
var yA = yAV[i];
// Adds the svg canvas
chart1 = d3.select("#graph table")
.append("tr")
.append("td")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Get the data
d3.json("graphdata.json", function(error, data) {
data.forEach(function(d) {
d[xA] = +d[xA];
d[yA] = +d[yA];
});
x.domain(d3.extent(data, function(d) { return d[xA]; }));
y.domain(d3.extent(data, function(d) { return d[yA]; }));
// Add the X Axis
chart1.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Add the Y Axis
chart1.append("g")
.attr("class", "y axis")
.call(yAxis);
// Add the valueline path.
chart1.append("path")
.attr("class", "line")
.attr("d", valueline(data));
});
}
Please help me out solving this problem.