D3.js v4单页插入独立柱状图与折线图出现NaN错误求助
Hey there! Let's dig into why your D3 bar and line charts are throwing that NaN error when run together—since they work fine alone, this is almost certainly a variable scope conflict getting in the way.
The Root Cause
That Error: attribute d: Expected number, "MNaN,116LNaN,117L…" means D3 is trying to generate a path (most likely for your line chart) but getting non-numeric values. The culprit here is probably shared variable names between your two charts. Looking at your code snippet, you declared var svg = d3.select(".simpleBar > svg") for the bar chart—if your line chart code also uses a variable named svg, the second declaration will overwrite the first. This breaks one of the charts by pointing it to the wrong SVG element, leading to broken coordinate calculations and NaNs.
Fixes to Try
Here are concrete steps to resolve this:
Rename SVG variables to be unique
Give each chart's SVG reference a distinct name so they don't overwrite each other:// Bar chart code const barSvg = d3.select(".simpleBar > svg"); // Use const instead of var for better scope control // Line chart code (assuming you're appending an SVG here) const lineSvg = d3.select("#lineGraph") .append("svg") .attr("width", 960) .attr("height", 500);Isolate other chart-specific variables
Don't stop at SVG—make sure scales, axes, and data variables are also unique to each chart. For example:// Bar chart scales const barXScale = d3.scaleBand().range([...]).domain([...]); const barYScale = d3.scaleLinear().range([...]).domain([...]); // Line chart scales const lineXScale = d3.scaleTime().range([...]).domain([...]); const lineYScale = d3.scaleLinear().range([...]).domain([...]);This prevents cross-contamination between your two charts' data mapping logic.
Use block scoping with
let/constinstead ofvarvarhas function-level scope, which makes it easy to accidentally overwrite variables across your code. Switching toconst(for variables that don't change) orlet(for variables that do) gives you block-level scope, reducing the chance of these conflicts entirely.
Example Corrected Code Snippet
Here's how your code might look after applying these fixes:
<div> <div>Simple Bar Chart</div> <div class="simpleBar"> <svg width="960" height="500"></svg> </div> </div> <div> <div>Line Chart</div> <div id="lineGraph"></div> </div> <script> // --------------- Bar chart code starts ----------------------- const barSvg = d3.select(".simpleBar > svg"); // Rest of bar chart logic uses barSvg, barXScale, barYScale, etc. // --------------- Line chart code starts ----------------------- const lineSvg = d3.select("#lineGraph") .append("svg") .attr("width", 960) .attr("height", 500); // Rest of line chart logic uses lineSvg, lineXScale, lineYScale, etc. </script>
This should resolve the NaN error by ensuring each chart operates on its own set of variables and SVG elements, without interfering with the other.
内容的提问来源于stack exchange,提问作者 margin = {top: 20

