【问题标题】:How to style d3.js selection as individual elements?如何将 d3.js 选择设置为单个元素?
【发布时间】:2016-05-13 09:20:18
【问题描述】:

我使用 D3.js 和 Leaflet,我想为每个圆圈设置不同的颜色。我有检查一个变量值并根据该变量返回该圆的填充颜色的函数。它仅在此代码之后显示一个圆圈,而不是所有数组(点):

 map._initPathRoot();

var svg = d3.select("#map").select("svg"),
    g = svg.append("g");
 var feature = g.selectAll("circle")
            .data(points)
            .enter().append('svg')
            .each(function (d, i) {        
                   d3.select(this).selectAll('circle')
                        .data([d])
                        .enter()
                        .append('circle')
                        .attr('r', 10)
                        .attr('stroke', 'white')
                        .attr('stroke-width', 1)
                        .attr('opacity', 0.8)
                        .style('fill', getFeatureColor(d)) //returns "red"  
            });
map.on("viewreset", update);
        update();

        function update() {
            feature.attr("transform",
                function (d) {
                    if (d !== undefined) {
                        return "translate(" +
                            map.latLngToLayerPoint(d.LatLng).x + "," +
                            map.latLngToLayerPoint(d.LatLng).y + ")";
                    }
                }
            )

        }
function getFeatureColor(d) {
        if(d.count>20) {
           return "red";
        }
        else {return "blue"}
}

【问题讨论】:

  • 什么是getFeatureColor(d)
  • 函数返回例如 "red";

标签: javascript d3.js


【解决方案1】:

我认为,不需要额外的 SVG 元素和对数据进行两次迭代。您可以直接使用点数组创建圆,如下所示。

希望这会有所帮助。

var feature = g.selectAll("circle")
  .data(points)
  .enter()
  .append('circle')
  .attr('r', 10)
  .attr('stroke', 'white')
  .attr('stroke-width', 1)
  .attr('opacity', 0.8)
  .style('fill', function(d){ return getFeatureColor(d) });  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 2016-12-21
    • 2013-09-15
    相关资源
    最近更新 更多