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

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

问题描述

我将 d3.js 代码粘贴到这里.

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

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

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 + ")");

根据 SO 此处的不同答案, 此处此处此处此处,解决方案似乎是以下之一:

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

  • 使用不同的变量名来保存 svgs,例如 svg1、svg2.. 等.我做过.
  • 使用描述的方法 这里.

   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.

推荐答案

在同一页面上使用多个 SVG 完全没有问题.举个例子:

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天全站免登陆