4

I have two histograms with .on("mouseover") listeners. Each is bound to a unique div id. For some reason they plot on the same SVG element.

I've tried to follow the pattern from "D3 Tips and Tricks" ...

<div id="Dx"></div>
   <script src="Dx.js" type="text/javascript"></script> 
<div id="Cpt"></div>
   <script src="Cpt.js" type="text/javascript"></script>

The code for the "Dx.js" chart is very similar to the "Cpt.js" chart.

I define the svg container and append to my unique div ID with

var svg = d3.select("#Cpt").append("svg")

later I svg.selectAll("#Cpt.bar") before data(data).enter().append("rect").

Can anyone help me understand what I'm doing wrong?

Colin
  • 930
  • 3
  • 19
  • 42

1 Answers1

5

It looks like you're including both scripts in the same namespace. This means that svg will be overwritten at some point. For the code that runs sequentially, this is not a problem because first everything related to the first chart will be done and then everything related to the second. The problem occurs when the asynchronous data loading handler functions run.

In particular, by the time they are run, all the sequential code has been executed. This means that svg now references the SVG you created last. This is what's used for all the drawing.

To fix, change the variable names to be different, e.g. svg1 in the first file and svg2 in the second. Alternatively, you can select the element you want explicitly at the start of the handler function, i.e.

var svg = d3.select("#Dx > svg");

and similarly in Cpt.js.

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
  • Thank you Lars. The first option worked (unique svg container names). Can you elaborate on what ("#Dx > svg") is doing? This didn't work. Also, I thought (incorrectly) that separate divs and separate files had their own independent namespace? Would a var= declaration make their scope local? – Colin Jan 05 '14 at 17:48
  • "#Dx > svg" selects the SVG element that is a child of "#Dx", which would correspond to the structure you've outlined. Does that come up empty for you? It works fine for me. To have separate namespaces, you could wrap the contents of the files in functions, i.e. `(function() { })();`. – Lars Kotthoff Jan 05 '14 at 18:06
  • It is my experience that ALL variable names needs to be changed, not just the `svg` select. The presence of any similar variables will cause the last chart to take over the others like a weed. – DeBraid Jul 28 '14 at 21:17
  • different variable names thing worked for me – Surya Tej Jan 04 '21 at 14:53