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....
I'm trying to create multiple graphs in one page. For now, only 1 bar graph displays. I have different divs each with their own unique ID's, so not sure what's going wrong here. 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.
Change this
d3.select("#chart1")
to
d3.select("#chart2")
And you should be good to go.
Multiple things
Change
const svg2 = d3.select("#chart1")
.append("svg")
.attr("width", w)
.attr("height", h);
to say d3.select("#chart2")
ect.
Number 2, is that you define w
and h
twice, which causes errors because you used const
.
Number 3
selectAll("text")
.data(dataset)
should use dataset1
and dataset2
.
I will say that these errors (mostly) can be determined by looking at the errors in the console
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.