[英]Why can't I display multiple graphs in one HTML page using D3?
Title.标题。 I'm a noob at this, and this has been frustrating me for 2 days now.
我对此很陌生,这让我沮丧了两天。 Not sure what I'm doing wrong.
不知道我做错了什么。 D3 is frustrating....
D3令人沮丧....
I'm trying to create multiple graphs in one page.我正在尝试在一页中创建多个图表。 For now, only 1 bar graph displays.
目前,仅显示 1 个条形图。 I have different divs each with their own unique ID's, so not sure what's going wrong here.
我有不同的 div,每个 div 都有自己唯一的 ID,所以不确定这里出了什么问题。 In addition to that, for some strange reason I can't add any text to the bars in the bargraphs I'm trying to create.
除此之外,由于某种奇怪的原因,我无法在我尝试创建的条形图中的条形图中添加任何文本。
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
TESTING
<body>
<div id="chart1" style = "position:static; left: 420px; bottom: 10px; float:left">
<h4>Positivity</h4>
<script>
const dataset1 = [32, 45, 22, 26, 23, 18, 29, 14, 9];
const w = 500;
const h = 100;
const chart1 = d3.select("#chart1")
.append("svg")
.attr("width", w)
.attr("height", h);
chart1.selectAll("rect")
.data(dataset1)
.enter()
.append("rect")
.attr("x", (d, i) => i * 30)
.attr("y", (d, i) => h - 3 * d)
.attr("width", 25)
.attr("height", (d, i) => 3 * d)
.attr("fill", "navy");
chart1.selectAll("text")
.data(dataset)
.enter()
.append("text")
.attr("x", (d,i)=>i*30)
.attr("y", (d,i)=>{return (h-(d*3)-3);})
.text(function (d){return d;});
</script>
</div>
<div id="chart2" style = "position:relative; left: 50px; bottom:0px; float:center">
<h4>Motivation</h4>
<script>
const dataset2 = [12, 31, 22, 17, 25, 18, 29, 14, 9];
const w = 500;
const h = 100;
const svg2 = d3.select("#chart2")
.append("svg")
.attr("width", w)
.attr("height", h);
svg2.selectAll("rect")
.data(dataset2)
.enter()
.append("rect")
.attr("x", (d, i) => i * 30)
.attr("y", (d, i) => h - 3 * d)
.attr("width", 25)
.attr("height", (d, i) => 3 * d)
.attr("fill", "navy");
svg2.selectAll("text")
.data(dataset)
.enter()
// Add your code below this line
.append("text")
.attr("x", (d,i)=>i*30)
.attr("y", (d,i)=>{return (h-(d*3)-3);})
.text(function (d){return d;});
// Add your code above this line
</script>
</div>
</body>
For your second bar chart you're selecting the wrong chart div.对于第二个条形图,您选择了错误的图表 div。
Change this改变这个
d3.select("#chart1")
to至
d3.select("#chart2")
And you should be good to go.你应该对 go 很好。
Multiple things多件事
Change改变
const svg2 = d3.select("#chart1")
.append("svg")
.attr("width", w)
.attr("height", h);
to say d3.select("#chart2")
ect.说
d3.select("#chart2")
等。
Number 2, is that you define w
and h
twice, which causes errors because you used const
.数字 2,是您定义
w
和h
两次,这会导致错误,因为您使用了const
。
Number 3 3 号
selectAll("text")
.data(dataset)
should use dataset1
and dataset2
.应该使用
dataset1
和dataset2
。
I will say that these errors (mostly) can be determined by looking at the errors in the console我会说这些错误(大部分)可以通过查看控制台中的错误来确定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.