3

I've got an array of objects called graphData (size varies). Each element contains all the information required to create a d3 graph, and I am able to successfully draw the graphs if I access graphData elements by hardcoding (i.e. graphdata[0], graphdata[1] etc).

The problem comes when I attempt to use a for loop to generate one graph for each of the elements. Looked around stackoverflow and the web, but the solutions are all about generating a fixed number of multiple graphs, not generating multiple graphs dynamically.

Below is my working code for generating one graph. What is the recommended way to generate x number of graphs automatically?

   var graphData = data.graph;

    var RADIUS = 15;

    var edgeData = graphData[0].edges;
    var nodeData = graphData[0].nodes;
    var stageNum = graphData[0].stage;


    var xScale = d3.scale.linear()
        .domain([d3.min(edgeData, function (d) {
            return d.start[0];
        }),
            d3.max(edgeData, function (d) {
                return d.start[0];
            })])
        .range([50, w - 100]);

    var yScale = d3.scale.linear()
        .domain([d3.min(edgeData, function (d) {
            return d.start[1];
        }),
            d3.max(edgeData, function (d) {
                return d.start[1];
            })])
        .range([50, h - 100]);

    var rScale = d3.scale.linear()
        .domain([0, d3.max(edgeData, function (d) {
            return d.start[1];
        })])
        .range([14, 17]);

    // already have divs with classes stage1, stage2... created.
    var svg = d3.select(".stage" + stageNum).append("svg")
        .attr({"width": w, "height": h})
        .style("border", "1px solid black");

    var elemEdge = svg.selectAll("line")
        .data(edgeData)
        .enter();

    var edges = elemEdge.append("line")
        .attr("x1", function (d) {
            return xScale(d.start[0]);
        })
        .attr("y1", function (d) {
            return yScale(d.start[1]);
        })
        .attr("x2", function (d) {
            return xScale(d.end[0]);
        })
        .attr("y2", function (d) {
            return yScale(d.end[1]);
        })
        .attr("stroke-width", 2)
        .attr("stroke", "black");


    var elemNode = svg.selectAll("circle")
        .data(nodeData)
        .enter();

    var nodes = elemNode.append("circle")
        .attr("cx", function (d) {
            return xScale(parseInt(d.x));
        })
        .attr("cy", function (d) {
            return yScale(parseInt(d.y));
        })
        .attr({"r": rScale(RADIUS)})
        .style("fill", "yellow")
        .style("stroke", "black");

3 Answers 3

3

Mike Bostock recommends implementing charts as reusable closures with methods. This would be an ideal implementation in your case as you want to have

  • multiple graphs with different data
  • potential reloading with new data (hopefully this is what you mean by dynamic?)

In broad strokes, what you want to do is wrap your code above into a function in very much the same way Mike describes in the post above, and then have data be an attribute of your closure. So here is some badly hacked code:

// your implementation here
var chart = function(){...}

var graphData = d3.json('my/graphdata.json', function(error, data){
  // now you have your data
});

// let's say you have a div called graphs
var myGraphs = d3.select('.graphs')
  .data(graphData)
  .enter()
  .append('g')
  //now you have g elements for each of your datums in the graphData array

//we use the saved selection above and call the chart function on each of the elements in the selection
myGraphs.call(chart);

//note that internally in your `chart` closure, you have to take in a selection
//object and process it(data is already bound to each of your selections from above):
function chart(selection) {
    selection.each(function(data) {
//...

Here is some more good reading on the topic.

1

Well you can try the following approach.

var graphData = data.graph;

//forEach will return each element for the callback, you can then make use  of the e1 to draw the graph.
graphData.forEach(function(e1){


   //graph code goes here.

});
3
  • What if we wanted to revise the data used for each element? D3 already provides the tools to avoid hacky for loops. It's literally what it was built to do! It's even in the explanation for joins: "Instead of telling D3 how to do something, tell D3 what you want". I'd shy away from doing that - especially when dealing with multiple graphs.
    – Max Alcala
    Sep 8, 2015 at 13:16
  • Yup, I agree with you. but the problem was broken for loop. I tried to fixed that. Your approach is way better than the approach in the question. +1 for that.
    – Fawzan
    Sep 8, 2015 at 13:18
  • It's all good. Once I learned how to make d3 do my dirty work I never wanted to go back. :)
    – Max Alcala
    Sep 8, 2015 at 13:20
1

providing this as your source array

//it's just a single circle in 3, 4
var stuff = [3, 4];
var source = [ [stuff, stuff], [stuff] ];

a bit of Array stuff

Array.prototype.max = function() {
    return Math.max.apply(null, this);
};

Array.prototype.min = function() {
    return Math.min.apply(null, this);
};

setup:

var dim = [];

source.forEach(function(elem){
    elem.forEach(function(circle){
        dim.push(circle.min());
        dim.push(circle.max());
    });
});

var min = dim.min();
var max = dim.max();

var x = d3.scale.linear()
        .domain([min, max])
        .scale([yourscale]);
var y = d3.scale.linear()
        .domain([min, max])
        .scale([yourscale]);

d3.select('body').selectAll('div')
    .data(source) //first step: a div with an svg foreach array in your array
    .enter()
    .append('div')
    .append('svg')
    .selectAll('circle') //second step: a circle in the svg for each item in your array
    .data(function(d){
        return d; //returns one of the [stuff] arrays
    }).enter()
    .append('circle')
    .attr('r', 5)
    .attr('cx', function(d){
        return x(d[0]);
    })
    .attr('cy', function(d){
        return y(d[1]);
    })
    .style('fill','blue');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.