Display multiple d3.js charts in a single html page

后端 未结 3 1994
情话喂你
情话喂你 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:07

    There is no need for repeating all the code, as you're doing right now. Don't repeat yourself.

    An easy alternative is wrapping all your D3 code in a function that has two parameters, selector and url:

    function draw(selector, url){
        //code here
    };
    

    Then, inside that function draw, you set the position of your SVG:

    var svg = d3.select(selector).append("svg")...
    

    And the URL you get the data:

    d3.json(ulr, function(error, root) {...
    

    After that, just call the draw function twice, with different arguments:

    draw(selector1, url1);
    draw(selector2, url2);
    

    Here is a demo, read it carefully to see how it works:

    draw("#svg1", "#data1");
    draw("#svg2", "#data2");
    
    function draw(selector, url){
    
    var data = d3.csvParse(d3.select(url).text())
    
    var width = 500,
        height = 150;
    
    var svg = d3.select(selector)
        .append("svg")
        .attr("width", width)
        .attr("height", height);
    
    var xScale = d3.scalePoint()
        .domain(data.map(function(d) {
            return d.name
        }))
        .range([50, width - 50])
        .padding(0.5);
    
    var yScale = d3.scaleLinear()
        .domain([0, d3.max(data, function(d) {
            return d.value
        }) * 1.1])
        .range([height - 20, 6]);
    
    var line = d3.line()
    	.x(function(d){ return xScale(d.name)})
    	.y(function(d){ return yScale(d.value)});
    	
    svg.append("path")
    	.attr("d", line(data))
    	.attr("stroke", "teal")
    	.attr("stroke-width", "2")
    	.attr("fill", "none");
    
    var xAxis = d3.axisBottom(xScale);
    var yAxis = d3.axisLeft(yScale);
    
    svg.append("g").attr("transform", "translate(0,130)")
        .attr("class", "xAxis")
        .call(xAxis);
    
    svg.append("g")
        .attr("transform", "translate(50,0)")
        .attr("class", "yAxis")
        .call(yAxis);
    
    }
    pre {
    display: none;
    }
    
    
    First SVG
    Second SVG
    name,value
    foo,8
    bar,1
    baz,7
    foobar,9
    foobaz,4
    name,value
    foo,1
    bar,2
    baz,3
    foobar,9
    foobaz,8

提交回复
热议问题