在单个html页面中显示多个d3.js图表 [英] Display multiple d3.js charts in a single html page

查看:651
本文介绍了在单个html页面中显示多个d3.js图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拥有粘贴此处的d3.js代码。



我试图在同一页面显示多个图表。虽然d3.js代码是相同的。从data1.json中说一个,从data2.json中说另一个。以下是困扰我的片段。

 < svg width =960height =960>< / SVG> 

< script src =https://d3js.org/d3.v4.min.js>< / script>
< script>
var svg2 = d3.select(svg),
margin = 20,
diameter = + svg2.attr(width),
g = svg2.append( attr(transform,translate(+ diameter / 2 +,+ diameter / 2 +));

根据SO 这里这里这里


I have the the d3.js code which is pasted here.

I am trying to display more than one graphs in the same page. Though the d3.js code is same. Say one from data1.json and the other from data2.json. Following is the snippet which is bothering me.

<svg width="960" height="960"></svg>

<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg2 = d3.select("svg"),
    margin = 20,
    diameter = +svg2.attr("width"),
    g = svg2.append("g").attr("transform", "translate(" + diameter / 2 + "," + diameter / 2 + ")");

As per different answers in SO here, here, here, here or here, the solution seems to be one of the following:

  • Use different variable name to hold svgs such as svg1, svg2.. etc.. which I have done.
  • Use a method as described here.

       var chart1 = d3.select("#area1")
           .append("svg")
    

Method two is not working for me, as it shows blank page.

How to resolve this. I am sure that I am not getting the syntax correctly.

解决方案

There's no problem at all using multiple SVGs on the same page. Here's an example:

var svg1 = d3.select("#svg1");
svg1.append("circle")
       .attr("cx",100)
       .attr("cy", 100)
       .attr("r", 90)
       .attr("fill", "red");
var svg2 = d3.select("#svg2");
svg2.append("circle")
       .attr("cx",100)
       .attr("cy", 100)
       .attr("r", 90)
       .attr("fill", "blue");

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="200" height="200" id="svg1"></svg>
<svg width="200" height="200" id="svg2"></svg>

这篇关于在单个html页面中显示多个d3.js图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆