d3JS: Drawing Line Segments from CSV

后端 未结 2 1799
时光取名叫无心
时光取名叫无心 2021-01-24 09:41

In d3Js, How would one draw basic line segments from a tsv file? Say the file declare, in one row of data, x1,y1,x2,y2. I want to draw two line segments as in the data below:<

2条回答
  •  抹茶落季
    2021-01-24 10:02

    The code below should work. Depending on your style, you may want to organize files and code differently, but the key part you must include is chain selectAll("line").data(data).enter().append("line"). This is the most frequent D3 idiom, and also the one that gives the hardest time to everyone learning D3 - especially to those that come from the background of procedural languages. You can look up D3 documentation, but I will also try to write down something on this topic later today.

    data/sampledata.tsv:

    same as yours.

    index.html:

    
    
        Two Lines
        
        
    
    
        

    Two Lines

    script.js:

    function load(){
        var svg = d3.select("body")
            .append("svg")
            .attr("width", 1000)
            .attr("height", 1000);
        d3.tsv("data/sampledata.tsv", function(error, data) {
            svg.selectAll("line")
                .data(data)
               .enter()
                .append("line")
                .attr("x1", function(d) { return (1000 * d.x0); })
                .attr("y1", function(d) { return (1000 * d.y0); })
                .attr("x2", function(d) { return (1000 * d.x1); })
                .attr("y2", function(d) { return (1000 * d.y1); })
                .attr("stroke-width", function(d) { return (d.weight); })
                .attr("stroke", "black");
        });
    };
    

    The code in action is here. IT produces following page:

    output page

提交回复
热议问题