D3图表:如何为SVG路径添加描边样式
Hey there! Adding stroke styles to your D3-generated SVG path is super simple—you just need to chain additional style or attribute calls right onto your existing code. Let me show you how to adjust your snippet:
Option 1: Using CSS Styles with .style()
This approach works great if you prefer CSS-like syntax, and it plays nicely with dynamic values based on your data:
path = group.append("svg:path") .attr("d", arc) .style("fill", function(d) { if (d.children) return color(d.name) else return "grey" }) // Add stroke styles here .style("stroke", "#222") // Solid dark gray stroke color .style("stroke-width", "1.5px") // Set stroke thickness .style("stroke-opacity", 0.8) // Optional: adjust stroke transparency .attr("display", function(d) { return d.depth ? null : "none"; }) .each(stash);
Option 2: Using SVG Attributes with .attr()
If you’d rather set direct SVG attributes (which is also fully valid), use .attr() instead:
path = group.append("svg:path") .attr("d", arc) .style("fill", function(d) { if (d.children) return color(d.name) else return "grey" }) // SVG attribute-based stroke settings .attr("stroke", "#222") .attr("stroke-width", 1.5) .attr("stroke-opacity", 0.8) .attr("display", function(d) { return d.depth ? null : "none"; }) .each(stash);
Dynamic Stroke Based on Data
Just like your fill color, you can make the stroke dynamic too! For example, use different stroke colors for parent vs. leaf nodes:
.style("stroke", function(d) { return d.children ? "#000" : "#666"; // Black for parent nodes, light gray for leaves })
The core idea here is leveraging D3’s method chaining—you can keep adding .style() or .attr() calls in sequence to set all the visual properties you need.
内容的提问来源于stack exchange,提问作者Jimmy

