使用d3.js和React渲染阿尔伯斯美国Choropleth图的正确视觉问题

lc8prwob  于 5个月前  发布在  React
关注(0)|答案(1)|浏览(40)

我试图找出出了什么问题,我的代码,因为我还没有能够产生任何东西,除了一个大广场的单一颜色,而我试图得到一个colorScale为每个元素与类“县”的这阿尔伯斯美国Map。
项目应该如下所示:https://choropleth-map.freecodecamp.rocks/
最奇怪的是,我验证了测试。
我使用d3.js并将其放在React 18组件中,并使用Babel通过另一个HTML文件进行渲染。
可能阻塞的代码段:

const createChoroplethMap = (counties, educationData, width, height, margins) => {
    // create SVG element
    const svg = d3.select("#chomap")
      .append("svg")
      .attr("width", width + margins.left + margins.right)
      .attr("height", height + margins.top + margins.bottom);
  
    // create projection and path generator
    const projection = d3.geoAlbersUsa();
    const pathGenerator = d3.geoPath().projection(projection);
  
    // create color scale
    const colorScale = d3.scaleQuantize()
      .domain([0, d3.max(educationData, d => d.bachelorsOrHigher)])
      .range(d3.schemeBlues[9]);
  
    // draw counties
    svg.selectAll(".county")
      .data(topojson.feature(counties, counties.objects.counties).features)
      .enter().append("path")
      .attr("class", "county")
      .attr("d", pathGenerator)
      .attr("fill", d => {
        const county = educationData.find(e => e.fips === d.id);
        console.log(county.bachelorsOrHigher)
        return colorScale(county.bachelorsOrHigher);
      })
      .attr("data-fips", d => d.id)
      .attr("data-education", d => {
        const county = educationData.find(e => e.fips === d.id);
        return county.bachelorsOrHigher;
      });
  
    // draw states
    svg.selectAll(".state")
      .data(topojson.feature(counties, counties.objects.states).features)
      .enter().append("path")
      .attr("class", "state")
      .attr("d", pathGenerator);
};

字符串
链接到codepen上的项目:https://codepen.io/reggr0y/pen/QWVoBOR
我试图找出我的代码出了什么问题,因为我不能生成任何东西,而不是一个单一颜色的大广场,而我试图得到一个colorScale为每个元素与类“县”的这张美国Map。

yqlxgs2m

yqlxgs2m1#

你可以通过两种方式修复你的codepen:
基于freecodecamp script,这意味着这个topojson已经被投影了。所以你可以简单地注解掉下面的projection调用。

const pathGenerator = d3.geoPath() //.projection(projection);

字符串
也许这是在你所遵循的教程/课程中提到的,如果不是,那么通常会预先投影阿尔伯斯美国Map,因为它是一个不遵循真实的地理的构造Map(例如阿拉斯加和夏威夷并不是真正的位置)。
this example中有一个更简单的预投影阿尔伯斯美国作为参考,没有choropleth机制。虽然projection用于数据覆盖,但在渲染代码中Mike Bostock没有使用projectionpath只是简单地定义为d3.geoPath()
也许,它也值得阅读通过问题/答案herehere从安德鲁里德。
第二,在县的顶部绘制州,因此填充none和笔划black

// draw states
svg.selectAll(".state")
  .data(topojson.feature(counties, counties.objects.states).features)
  .enter().append("path")
  .attr("class", "state")
  .attr("d", pathGenerator)
  .attr("fill", "none") // <-- add 
  .attr("stroke", "black"); // <-- add


这是删除投影的结果-请注意,您只看到黑人州,因为它们覆盖了县:
x1c 0d1x的数据
下面是对状态填充和笔画进行调整的结果(意味着您对填充应用的colorScale是正确的):


相关问题