I am not sure what am I doing wrong but I am trying to create data-driven svg
<rect>
. The code is following
var x = [];
for (var i = 0; i < 20; i ) {
x.push(Math.floor(100 * Math.random()));
};
const newData = x;
const s1 = d3.select("svg")
.selectAll("rect")
.data(newData)
.enter()
.append("rect")
.attr("width", (d, i) => { return d })
.attr("y", (d, i) => { return i * 50 })
.attr("x", 0)
.attr("height", 40)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>
<body>
<link rel="stylesheet" href="style.css">
</link>
<script src="_d3.js"></script>
<nav>
<h1>Hello Reader</h1>
<h2>Day1</h2>
<p>Monday</p>
<h2>Day2</h2>
<p>Tuesday</p>
<h2>Day3</h2>
<p>Wednesday</p>
<h2>Day4</h2>
<p>Thursday</p>
</nav>
<main>
<h1>Current Period</h1>
<svg width="900" height="600">
</svg>
<h1>YTD</h1>
</main>
</body>
</html>
However, the above code does not create any rect
at all whereas I was expecting to see 20 rect
s inside
<svg width="900" height="600">
</svg>
The above code returns this
CodePudding user response:
Move your script (_d3.js
) to just before the closing </body>
tag. The d3.select("svg")
must be returning an empty selection, because your script starts executing before the <svg>
is rendered, so there's no svg
to select. (For more, see this answer about where to include your script tags)
var x = []
for (var i = 0; i < 20; i ) {
x.push(Math.floor(100 * Math.random()))
}
const newData = x
const s1 = d3
.select('svg')
.selectAll('rect')
.data(newData)
.enter()
.append('rect')
.attr('width', (d, i) => {
return d
})
.attr('y', (d, i) => {
return i * 50
})
.attr('x', 0)
.attr('height', 40)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>
<body>
<nav>
<h1>Hello Reader</h1>
<h2>Day1</h2>
<p>Monday</p>
<h2>Day2</h2>
<p>Tuesday</p>
<h2>Day3</h2>
<p>Wednesday</p>
<h2>Day4</h2>
<p>Thursday</p>
</nav>
<main>
<h1>Current Period</h1>
<svg width="900" height="600"></svg>
<h1>YTD</h1>
</main>
<script src="_d3.js"></script>
</body>
</html>