使用d3.js和React渲染Albers美国分级统计图的视觉异常问题
问题:React 18中D3.js绘制Albers美国分级统计图仅显示单一颜色
我正在排查代码问题:尝试用d3.js在React 18组件中实现Albers美国分级统计图,期望为每个class为"county"的元素应用colorScale,但目前仅显示单一颜色的大矩形。项目预期效果是美国各县按本科及以上学历占比分级着色的地图,奇怪的是测试已通过。我使用Babel通过另一个HTML文件进行渲染。
问题代码片段
const createChoroplethMap = (counties, educationData, width, height, margins) => { // 创建SVG元素 const svg = d3.select("#chomap") .append("svg") .attr("width", width + margins.left + margins.right) .attr("height", height + margins.top + margins.bottom); // 创建投影和路径生成器 const projection = d3.geoAlbersUsa(); const pathGenerator = d3.geoPath().projection(projection); // 创建颜色比例尺 const colorScale = d3.scaleQuantize() .domain([0, d3.max(educationData, d => d.bachelorsOrHigher)]) .range(d3.schemeBlues[9]); // 绘制县 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; }); // 绘制州 svg.selectAll(".state") .data(topojson.feature(counties, counties.objects.states).features) .enter().append("path") .attr("class", "state") .attr("d", pathGenerator); };
排查方向
- 投影适配问题:AlbersUsa投影需要将地图适配到SVG容器,原代码未做适配,可能导致所有地理要素重叠。尝试修改投影代码:
const projection = d3.geoAlbersUsa() .fitSize([width, height], topojson.feature(counties, counties.objects.counties)); - 数据匹配问题:检查
d.id(县FIPS)和e.fips(教育数据FIPS)的格式是否一致,比如是否存在前导零差异。若匹配失败,county会为undefined,导致颜色比例尺返回默认值。可以添加容错处理:.attr("fill", d => { const county = educationData.find(e => e.fips === d.id); return county ? colorScale(county.bachelorsOrHigher) : "#cccccc"; }) - 控制台报错检查:打开浏览器控制台,查看是否有
county为undefined的报错,或TopoJSON转换错误的信息。 - SVG尺寸验证:确认
width、height和margins参数传递正确,确保SVG容器有足够的显示空间。
内容的提问来源于stack exchange,提问作者Reggroy
相关产品推荐
相关产品推荐

