如何让D3.js识别CSV中的十六进制颜色并为矩形着色?
D3.js 矩形填充CSV中十六进制颜色失败问题
已实现的数据加载代码
我已成功通过以下代码加载CSV数据:
// Read the CSV file and parse the data d3.csv("Data.csv").then(function(data) { // Store the parsed data in the variable. var parsedData = data; // Convert the data to the format expected by the visualization code. var nodeData = parsedData.map(function(d) { console.log("color: ", d.color); // add this line to check the color value return { occ: d.occ, position: [+d.x * smaller_width, +d.y * smaller_height], parentPosition: [+d.parent_x * smaller_width, +d.parent_y * smaller_height], color: d.color }; });
问题场景
后续编写代码利用CSV中的坐标绘制矩形并添加文本标签,但尝试使用CSV中存储的十六进制颜色为矩形着色时始终失败,尝试代码如下:
d3.select(this) .append("rect") .classed("rect", true) .attr("occ", `rect-${d.occ}`) .attr("x", -10) .attr("y", -20) .attr("width", 20) .attr("height", 40) .style("fill", `text-${d.color}`) // 尝试过${d.color}、color、d.color等多种写法均无效 .style("paint-order", "stroke fill markers");
怀疑是style与attr函数处理数据元素d的方式差异导致问题。
解决方案与排查步骤
1. 移除无效前缀并修正颜色赋值
代码中style("fill", text-${d.color})的text-前缀完全多余,直接使用d.color即可。SVG的fill属性用attr或style设置都有效,优先用attr更符合SVG属性规范:
// 两种写法都可行 .attr("fill", d.color) // 或 .style("fill", d.color)
2. 确认数据绑定有效性
确保这段绘制代码处于数据绑定的回调链中(比如.data(nodeData).enter()之后),保证d能正确指向当前数据对象。如果是在.each()或事件回调中,也要确认d的作用域正确。
3. 清洗颜色数据
检查控制台console.log("color: ", d.color)的输出:
- 如果颜色值带引号(比如
"#ff0000"),在数据处理阶段去除引号:
color: d.color.trim().replace(/"/g, '')
- 如果有多余空格,用
trim()去除。
4. 修正后完整示例
数据处理阶段:
var nodeData = parsedData.map(function(d) { console.log("color: ", d.color); return { occ: d.occ, position: [+d.x * smaller_width, +d.y * smaller_height], parentPosition: [+d.parent_x * smaller_width, +d.parent_y * smaller_height], color: d.color.trim().replace(/"/g, '') // 清洗颜色值 }; });
绘制矩形阶段:
// 确保在数据绑定的上下文内 d3.select("svg") .selectAll(".rect-container") .data(nodeData) .enter() .append("g") .attr("transform", d => `translate(${d.position[0]}, ${d.position[1]})`) .each(function(d) { d3.select(this) .append("rect") .classed("rect", true) .attr("occ", `rect-${d.occ}`) .attr("x", -10) .attr("y", -20) .attr("width", 20) .attr("height", 40) .attr("fill", d.color) // 直接使用清洗后的颜色值 .style("paint-order", "stroke fill markers"); });
内容的提问来源于stack exchange,提问作者COOKIES
相关产品推荐
相关产品推荐

