如何在d3中绘制多边形内的图像

时间:2017-05-18 06:16:09

标签: javascript d3.js charts

大家好我正在使用带有多边形的d3图表我有一个地图结构d3图表并为了显示工具提示而绘制一个圆圈现在我的需要是我需要显示一个图像' https://i.stack.imgur.com/O9xB5.png&# 39;更换圆圈所以当鼠标悬停在图像上时我会显示工具提示而另一个需要显示' State Abbr'内部多边形,如Ak,TD,PD ......  .help在这里做这个我附上我的代码文件

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v3.min.js"></script>
<style type="text/css">

/* On mouse hover, lighten state color */
path:hover {
    fill-opacity: .7;
}

/* Style for Custom Tooltip */
div.tooltip {   
    position: absolute;           
    text-align: center;           
    width: 60px;                  
    height: 28px;                 
    padding: 2px;             
    font: 12px sans-serif;        
    background: white;   
    border: 0px;      
    border-radius: 8px;           
    pointer-events: none;         
}

/* Legend Font Style */
body {
    font: 11px sans-serif;
}

/* Legend Position Style */
.legend {
    position:absolute;
    left:800px;
    top:350px;
}

</style>
</head>
<body>
<script type="text/javascript">         
//Width and height of map
var width = 960;
var height = 500;   
// D3 Projection
var projection = d3.geo.albersUsa()
                   .translate([width/2, height/2])    
                   .scale([1000]);         

// Define path generator
var path = d3.geo.path()               
             .projection(projection);      

// Define linear scale for output
var color = d3.scale.linear()
              .range(["green","red"]);

var legendText = ["Population Present", "Population Absent"]; 
var svg = d3.select("body")
            .append("svg")

            .attr("width", width)
            .attr("height", height);
var div = d3.select("body")
            .append("div")   

            .attr("class", "tooltip")  

             .style("opacity", 0);

// Load in my states data!
d3.csv("Population_education.csv", function(data) {

// Load GeoJSON data and merge with states data
d3.json("us-states.json", function(json) {

// Loop through each state data value in the .csv file
for (var i = 0; i < data.length; i++) {
    // Grab State Name
    var dataState = data[i].SiteState;

    // Get Population
    var dataPop = data[i].Population;

    // Grab data value 
    if(data[i].Members > 0) {
    var dataValue = 1;
    } 
    else { var dataValue = 0;}
    // Find the corresponding state inside the GeoJSON
    for (var j = 0; j < json.features.length; j++)  {
        var jsonState = json.features[j].properties.name;
        if (dataState == jsonState) {
        // Copy the data value into the JSON
        json.features[j].properties.MembersPresent = dataValue;
        json.features[j].properties.pop = +dataPop;
        // Stop looking through the JSON
        break;
        }

    }
}

// Get Max and Min Population and update colorscale
var max = d3.max(json.features, function(d) { return d.properties.pop });
var min = d3.min(json.features, function(d) { return d.properties.pop })

color.domain([min, max]); // setting the range of the input data

// Bind the data to the SVG and create one path per GeoJSON feature
svg.selectAll("path")
    .data(json.features)
    .enter().append("path")
        .attr("d", path)
        .style("stroke", "#fff")
        .style("stroke-width", "1")       
        .style("fill", function(d) {
            return color(d.properties.pop)
        });



// Map the cities I have lived in!
d3.csv("Population_education.csv", function(data) {

svg.selectAll("circle")
    .data(data)
    .enter()
    .append("circle")
    .attr("cx", function(d) {
        if (d.AvgLng != 0 && d.AvgLat != 0)
        return projection([d.AvgLng, d.AvgLat])[0];
    })
    .attr("cy", function(d) {
    if (d.AvgLng != 0 && d.AvgLat != 0)
        return projection([d.AvgLng, d.AvgLat])[1];
    })
    .attr("r", function(d) {
        return 3;
    })
        .style("fill", "rgb(217,91,67)")    
        .style("opacity", 0.45) 
    .on("mouseover", function(d) {      
        div.transition()        
           .duration(200)      
           .style("opacity", .9);
           div.html("State:" + d['State Abbr'] + "<br/>"  + "Pop:" + d.Population)
           .style("left", (d3.event.pageX) + "px")     
           .style("top", (d3.event.pageY - 28) + "px");    
    })   
    .on("mouseout", function(d) {       
        div.transition()        
           .duration(500)      
           .style("opacity", 0);   
    });
}); 

var legend = d3.select("body").append("svg")
                .attr("class", "legend")
                .attr("width", 140)
                .attr("height", 200)
                .selectAll("g")
                .data(color.domain().slice().reverse())
                .enter()
                .append("g")
                .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

    legend.append("rect")
          .attr("width", 18)
          .attr("height", 18)
          .style("fill", color);

    legend.append("text")
          .data(legendText)
          .attr("x", 24)
          .attr("y", 9)
          .attr("dy", ".35em")
          .text(function(d) { return d; });
    });

});
</script>
</body>
</html> 

数据

Population_education.csv

RowID,SiteState,State Abbr,AvgLat,AvgLng,Population
1,Alabama,AL,32.806671,-86.79113,28
2,Arizona,AZ,33.729759,-111.431221,11704
3,California,CA,36.116203,-119.681564,4356448
4,Colorado,CO,39.059811,-105.311104,374435
5,Connecticut,CT,41.597782,-72.755371,455966
6,Florida,FL,27.766279,-81.68678300000001,442537
7,Georgia,GA,33.040619,-83.643074,1339081
8,Illinois,IL,40.349457,-88.986137,29
9,Indiana,IN,39.849426,-86.258278,1525124
10,Iowa,IA,42.011539,-93.210526,185146
11,Kansas,KS,38.5266,-96.72648599999999,129301
12,Kentucky,KY,37.66814,-84.670067,621047
13,Louisiana,LA,31.169546,-91.867805,170568
14,Maine,ME,44.693947,-69.381927,222966
15,Maryland,MD,39.063946,-76.80210099999999,256966
16,Massachusetts,MA,42.230171,-71.530106,27
17,Michigan,MI,43.326618,-84.536095,27
18,Minnesota,MN,45.694454,-93.900192,11
19,Missouri,MO,38.456085,-92.28836800000001,420415
20,Nevada,NV,38.313515,-117.055374,309799
21,New Hampshire,NH,43.452492,-71.563896,195948
22,New Jersey,NJ,40.298904,-74.521011,241039
23,New Mexico,NM,34.840515,-106.248482,1945
24,New York,NY,42.165726,-74.94805100000001,1075153
25,North Carolina,NC,35.630066,-79.80641900000001,14
26,Ohio,OH,40.388783,-82.764915,1526404
27,Oregon,OR,44.572021,-122.070938,11
28,Pennsylvania,PA,40.590752,-77.209755,197
29,South Carolina,SC,33.856892,-80.945007,45
30,Tennessee,TN,35.747845,-86.692345,446667
31,Texas,TX,31.054487,-97.563461,736672
32,Vermont,VA,37.769337,-78.169968,2324640
33,Washington,WA,47.400902,-121.490494,141319
34,West Virginia,WV,38.491226,-80.954453,128275
35,Wisconsin,WI,44.268543,-89.616508,405942
36,Alaska,AK,0,0,0
37,Arkansas,AR,0,0,0
38,Delaware,DE,0,0,0
39,District of Columbia,DC,0,0,0
40,Hawaii,HI,0,0,0
41,Idaho,ID,0,0,0
42,Mississippi,MS,0,0,0
43,Montana,MT,0,0,0
44,Nebraska,NE,0,0,0
45,North Dakota,ND,0,0,0
46,South Dakota,SD,0,0,0
47,Utah,UT,0,0,0
48,Virginia,VT,0,0,0
49,Wyoming,WY,0,0,0
50,Oklahoma,OK,0,0,0
51,Rhode Island,RI,0,0,0

我的us-states.json与以下链接https://raw.githubusercontent.com/alignedleft/d3-book/master/chapter_12/us-states.json

相同

1 个答案:

答案 0 :(得分:3)

为每个多边形添加图像和工具提示的代码。

paths.each(function(d) {
    if (this.getTotalLength() > 0) {
      var midPoint = path.centroid(d);          
      svg.append("svg:image")
        .attr("height", "15px")
        .attr("width", "15px")
        .attr("xlink:href", "https://i.stack.imgur.com/O9xB5.png")
        .attr("transform", "translate(" + midPoint[0] + ",  " + midPoint[1] + ")")
        .append("title")
        .text(d.properties.abbr);
      svg.append("svg:text")
        .attr("x", midPoint[0])
        .attr("y", midPoint[1])
        .text(d.properties.abbr);
    }
});

JSFiddle

要在数据中包含abbr详细信息,代码如下所示。

// Find the corresponding state inside the GeoJSON
for (var j = 0; j < json.features.length; j++) {
    var jsonState = json.features[j].properties.name;
    if (dataState == jsonState) {
       // Copy the data value into the JSON
       json.features[j].properties.MembersPresent = dataValue;
       json.features[j].properties.pop = +dataPop;
       json.features[j].properties.abbr = data[i]["State Abbr"];
       // Stop looking through the JSON
       break;
    }
}