Display multiple d3.js charts in a single html page

后端 未结 3 1997
情话喂你
情话喂你 2020-12-16 02:23

I have the the d3.js code which is pasted here.

I am trying to display more than one graphs in the same page. Though the d3.js code is same. Say one from data1.json

3条回答
  •  半阙折子戏
    2020-12-16 03:00

    If the two charts use the same code, I think the most d3-like way to go about it would be

    var width = 960,
        height = 960,
        margin = 30;
    
    var svgs = d3.select('#area1')
        .selectAll('svg')
        .data([json1, json2])
        .enter()
        .append('svg')
        .attr('width', width)
        .attr('height', height)
    
    svgs.append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
        .each(function(d) {console.log(d)}) // will log json1, then json2
    

    You'll then have json1 and json2 bound to each of the newly appended svgs, and all code that follows will be done to both.

    var width = 200,
        height = 100,
        margin = 30;
    
    var svgs = d3.select('#area1')
        .selectAll('svg')
        .data([{text:'thing1'}, {text:'thing2'}])
        .enter()
        .append('svg')
        .attr('width', width)
        .attr('height', height);
    
    svgs.append("text")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
        .text(function(d) {return d.text});
    
    

提交回复
热议问题