简体   繁体   中英

How would this d3 code be updated from v3 to v4?

var url = 'https://gist.githubusercontent.com/
d3byex/65a128a9a499f7f0b37d/raw/176771c2f08dbd3431009ae27bef9b2f2fb5
6e36/us-states.json';

d3.json(url, function (error, data) {
    var path = d3.geo.path();
    svg.selectAll('path')
        .data(data.features)
        .enter()
        .append('path')
        .attr('d', path);
});

I'm trying to keep my code as up to date as possible so that I can begin using d3v4, but many textbooks are out of date.

The example above works fine with d3v3 (as demonstrated here: http://bl.ocks.org/d3byex/378d68f27a1cc144aa8a )

I know that .geo.path() will need to be updated to .geoPath(), but I'm missing at least one other update that needs to be made in order for this to be compliant with d3v4.

In d3v3 d3.geo.path used a default projection, the US Albers projection:

d3.geo.path()

Creates a new geographic path generator with the default settings: the albersUsa projection and a point radius of 4.5 pixels. ( link )

In d3v4, the default projection is a null projection:

path.projection([projection]) <>

If a projection is specified, sets the current projection to the specified projection. If projection is not specified, returns the current projection, which defaults to null. ( link )

This is why your data is scaled and centered appropriately in your d3v3 map, though it wouldn't be if it were of anywhere else.

The d3v4 default projection for a geoPath simply converts the coordinates in the data to svg coordinates with no transformation or projection. Consequently, in d3v4, your data needs a projection to be properly rendered (it is drawn, but as all the x coordinates in the US are negative, it's off screen). To use the default projection from v3 (a US Albers composite projection) you can use:

var projection = d3.geoAlbersUsa();
var path = d3.geoPath().projection(projection);

And then go about everything else as you are:

  var width = 950, height = 500; var svg = d3.select('body') .append('svg') .attr("width",width) .attr("height",height); var url = 'https://gist.githubusercontent.com/d3byex/65a128a9a499f7f0b37d/raw/176771c2f08dbd3431009ae27bef9b2f2fb56e36/us-states.json'; d3.json(url, function (error, data) { var projection = d3.geoAlbersUsa() var path = d3.geoPath().projection(projection); svg.selectAll('path') .data(data.features) .enter() .append('path') .attr('d', path); }); 
  <script src="http://d3js.org/d3.v4.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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