d3.js two graphs on same page is on top of each other

岁酱吖の 提交于 2020-01-06 12:37:04

问题


I have 2 graphs each in separate angular directive

<chart1 ng-model="data" style="display:block;" id="plot1" class="ng-pristine ng-valid">
<svg width="960" height="500" style="right: 0px;">Some data</svg>
</chart1>
<chart2 ng-model="data" style="display:block;" id="plot1" class="ng-pristine ng-valid">
<svg width="960" height="500" style="right: 0px;">Some data</svg>
</chart2>

chart1 generation of svg:

           var svg = d3.select("#plot1").append("svg")
               .attr("width", width + margin.left + margin.right)
               .attr("height", height + margin.top + margin.bottom).style({'right': '0'});

chart 2 :

               var svg = d3.select("#plot2").append("svg")
               .attr("width", width + margin.left + margin.right)
               .attr("height", height + margin.top + margin.bottom).style({'right': '0'});

for some reason those two graphs ends on top of each other, in html i can see that svg is stylled as position: absolute. if i remove this style everything works, but it i sstyle this way for a reason probably...

i come accross this guid: http://www.d3noob.org/2013/07/arranging-more-than-one-d3js-graph-on.html

but it didnt helped.

How can i solve this problem?


回答1:


I notice that both of your chart tags are using the same id id="plot1".

I'm not much of an expert on these things, but I'm fairly sure that id's should be unique.

From w3school: "The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document)."




回答2:


You might also need to use two different variables var svg1 and var svg2 in your scripts, because you know, the async functions will have trouble to find the correct svg element.


Story:

Google search took me here for having trouble to place two SVGs on a single DOM. Just check if this is your case.

The problem I faced:

  • I had two chart elements on the same page; the ids, names were different.
  • Both of them were at different portion of page, (generated using a template engine[GSP])
  • Both the blocks had a similar script. The content was loaded from JSON API.
  • The chart contents were overlapped

The actual problem:

  • The variable names were messed up. Both the scripts used same variable var svg=... to refer to SVG element. The JSON response in async function from server was going to second SVG because its script reassigned var svg=...

The solution:

I used two different variables: var svg1=... and var svg2=...



来源:https://stackoverflow.com/questions/21581277/d3-js-two-graphs-on-same-page-is-on-top-of-each-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!