繁体   English   中英

根据数据属性更改d3.js符号大小

[英]Changing d3.js symbol size based on the attribute of data

我正在尝试根据数据集中的属性“ WinsNoms”的值来缩放符号的大小。 该图表将被渲染,但不会根据“ winsNoms”进行缩放。 谁能帮我我在哪里错了?

var sizeExtent = d3.extent(data, function(d) { return d.WinsNoms });
var sizeScale = d3.scale.linear()
                .domain(sizeExtent)
                .range([5,15]);

var symbolTypesx = {
    "cross": d3.svg.symbol().type("cross").size(function(d) { return sizeScale(d.WinsNoms);}),
    "circle": d3.svg.symbol().type("circle").size(function(d) { return sizeScale(d.WinsNoms);})
};

svg2.selectAll("path")
    .data(data)
    .enter().append("path")
    .attr("class", "dot")
    // position it, can't use x/y on path, so translate it
    .attr("transform", function(d) { 
        return "translate("+xScale(d.imdbRating)+","+yScale(d.imdbVotes)+")"; 
    })
   .attr("d", function(d,i){
        if (d.IsGoodRating === 0)
        { // circle if bar === 0
            return symbolTypesx.circle();
        }
        else
        {
            return symbolTypesx.cross();
        }
    })
    // fill based on goo and foo
   .style("fill", function(d,i){
        if (d.IsGoodRating === 0)
                return "red";
            else
                return "blue";
    });

调用它时,需要将基准传递到symbol函数中:

return symbolTypesx.circle(d);

运行代码:

 <!DOCTYPE html> <html> <head> <script data-require="d3@3.5.17" data-semver="3.5.17" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script> </head> <body> <script> var svg2 = d3.select("body") .append("svg") .attr("width", 500) .attr("height", 500); var data = [{ WinsNoms: Math.random(), GoodRathing: Math.random() > 0.5 ? 1 : 0 }, { WinsNoms: Math.random(), GoodRathing: Math.random() > 0.5 ? 1 : 0 }, { WinsNoms: Math.random(), GoodRathing: Math.random() > 0.5 ? 1 : 0 }, { WinsNoms: Math.random(), GoodRathing: Math.random() > 0.5 ? 1 : 0 }, { WinsNoms: Math.random(), GoodRathing: Math.random() > 0.5 ? 1 : 0 }]; var sizeExtent = d3.extent(data, function(d) { return d.WinsNoms }); var sizeScale = d3.scale.linear() .domain(sizeExtent) .range([5, 250]); var symbolTypesx = { "cross": d3.svg.symbol().type("cross").size(function(d) { return sizeScale(d.WinsNoms); }), "circle": d3.svg.symbol().type("circle").size(function(d) { return sizeScale(d.WinsNoms); }) }; svg2.selectAll("path") .data(data) .enter() .append("path") .attr("class", "dot") .attr("transform", function(d,i) { return "translate(" + ((i * 20) + 10) + "," + ((i * 20) + 10) + ")"; }) .attr("d", function(d, i) { if (d.IsGoodRating === 0) { // circle if bar === 0 return symbolTypesx.circle(d); } else { return symbolTypesx.cross(d); } });; </script> </body> </html> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM