我试图弄清楚我的代码出了什么问题,因为当我尝试为这个 Albers 的“县”类的每个元素获取一个 colorScale 时,除了单一颜色的大正方形之外我无法生成任何其他东西美国地图。
项目应该是这样的: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 时,除了单一颜色的大正方形之外我无法生成任何其他东西地图
您可以通过两种方式修复代码笔:
基于 freecodecamp script 暗示这个 topojson 已经被投影。所以你可以简单地注释掉下面的
projection
调用。
const pathGenerator = d3.geoPath() //.projection(projection);
也许这是在您正在学习的教程/课程中提到的,如果没有,预投影 Albers USA 地图是很常见的,因为它是一个不遵循真实地理的构造地图(例如阿拉斯加和夏威夷不是真的他们在哪里)。
在this example中有一个更简单的预先投影的Albers USA作为参考,没有等值线力学。虽然
projection
用于数据叠加,但在渲染代码中请注意 Mike Bostock 不使用 projection
并且 path
被简单地定义为 d3.geoPath()
.
也许,也值得通读 Andrew Reid here 和 here 的问题/答案。
其次,你把州画在县的顶部,所以填充
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
这是移除投影的结果 - 请注意,您只看到黑色州,因为它们覆盖了县:
这是对状态填充和描边进行调整的结果(意味着您对填充应用
colorScale
是正确的):