Filter data in d3 to draw either circle or square

后端 未结 2 1145
梦如初夏
梦如初夏 2020-12-08 15:56

I\'m having a bit of trouble understand selections and filtering in d3. Let\'s say I have a simple array:

data = [1, 2, 6, 3, 4]

I want to

2条回答
  •  渐次进展
    2020-12-08 16:22

    It is also possible use the data to conditionally create circles or rectangles by providing a function argument to the append function

        .append(function(d, i){
            if (something to do with d) {
                ... return an SVG circle element
            } else {
                ... return an SVG rectangle element
            }
        })
    

    e.g. like this

    var data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    var svg = d3.select("body").append("svg");
    
    function createSvgEl(name) {
        return document.createElementNS('http://www.w3.org/2000/svg', name);
    }
    
    svg
        .selectAll(".shapes")
        .data(data)
        .enter()
        .append(function(d, i){
            if (d <= 4) {
                return createSvgEl("circle");
            } else {
                return createSvgEl("rect");
            }
        });
    
    svg.selectAll("circle")
            .attr("cx", function(d, i){ return (i+1) * 25; })
            .attr("cy", 10)
            .attr("r", 10);
    
    svg.selectAll("rect")
            .attr("x", function(d, i){ return (i+1) * 25; })
            .attr("y", 25)
            .attr("width", 10)
            .attr("height", 10);
    

提交回复
热议问题