D3 v5.16散点图:使用符号替代点无显示问题求助
Hey there! Let's figure out why your custom symbols aren't showing up in your D3 scatter plot. I've spotted a couple of key issues in your code, plus a quick sanity check to ensure everything lines up:
Critical Issues & Fixes
1. <path> elements don't support x/y attributes
D3's symbol generator creates path data centered at the origin (0,0). Browsers ignore x and y attributes on SVG <path> elements—instead, you need to use the transform attribute to translate each symbol to its correct position on the plot.
2. Symbol size requires a numeric value, not a string
You're passing "200" (a string) to the size() method, but it expects a number. This invalid input prevents D3 from calculating the symbol's dimensions correctly.
Corrected Code
Here's your updated setPointsToCanvas function with these fixes applied:
setPointsToCanvas(canvas, data, scales, x_label, y_label, lang) { canvas .selectAll("marks") .data(data) .enter() .append("path") // Use transform to position each symbol .attr("transform", d => { const xPos = scales.xScale(d.value_x); const yPos = scales.yScale(parseFloat(d.value_y)); return `translate(${xPos}, ${yPos})`; }) .attr( "d", d3 .symbol() .type(d3.symbolCross) .size(200) // Numeric value for size ) // Optional: Add styling to make symbols visible .attr("fill", "none") .attr("stroke", "#2c3e50") .attr("stroke-width", 2); }
Quick Additional Check
Make sure your canvas variable is selecting an SVG element (not an HTML <canvas> element!). D3 symbols are SVG-based, so if you're targeting an HTML canvas, this approach won't work. You should have something like const canvas = d3.select("#your-scatter-plot-svg"); in your code.
Once you apply these changes, your cross symbols should render properly at each data point!
内容的提问来源于stack exchange,提问作者José Carlos

