Background image to SVG choropleth map using D3

fhbi

I'm putting together a choropleth map in D3 of U.S. States and already have the code to render the map with solid colored backgrounds using fill.

However, I want the fill of the state paths to be an image. I tried setting the path background-image to the img's URL, but that didn't work.

How can I do this? I'd also like to fill each state a different image.

var svg = d3.select("#map").append("svg")
    .attr("width", width)
    .attr("height", height);

svg.append("rect")
    .attr("class", "background")
    .attr("fill","none")
    .attr("width", width)
    .attr("height", height);

var g = svg.append("g")
    .attr("class", "states");

$(document).ready(function() {
    d3.json("us-states.json", function(json) {
        var features = json.features;
        g.selectAll("path")
            .data(json.features)
            .enter()
            .append("path")
            .attr("d", path)
            .attr("fill", "purple")
            .attr("stroke","white")
            .attr("stroke-width", 1);
    });
});
DSA beginner

As Superboggly points out, first define a pattern, then use it.

Definition example:

<defs>
    <pattern id="chloroplethbackground" patternUnits="userSpaceOnUse" width="??" height="??">
        <image xlink:href="bg.jpg" x="0" y="0" width="??" height="??" />
    </pattern>
</defs>

Then set your fill to url(#chloroplethbackground)

So it will be:

var svg = d3.select("#map").append("svg")
    .attr("width", width)
    .attr("height", height);

svg.append("rect")
    .attr("class", "background")
    .attr("fill","none")
    .attr("width", width)
    .attr("height", height);

var g = svg.append("g")
    .attr("class", "states");

$(document).ready(function() {
    d3.json("us-states.json", function(json) {
        var features = json.features;
        g.selectAll("path")
            .data(json.features)
            .enter()
            .append("path")
            .attr("d", path)
            .attr("fill", "url(#chloroplethbackground)")
            .attr("stroke","white")
            .attr("stroke-width", 1);
    });
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related