Dynamically generating multiple d3 svg graphs

2020-06-06 05:31发布

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条回答
来,给爷笑一个
2楼-- · 2020-06-06 06:02

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.

查看更多
我只想做你的唯一
3楼-- · 2020-06-06 06:04

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.

});
查看更多
够拽才男人
4楼-- · 2020-06-06 06:16

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');
查看更多
登录 后发表回答