Attempting to grasp D3 through this video has been a challenging experience, particularly when attempting to load an external file. The code snippets are provided below:
index.html
<html>
<head>
<meta charset="utf-8">
<title>D3 Example</title>
<script type="text/javascript" src="https://d3js.org/d3.v4.min.js"></script>
<body>
<script>
d3.json("mydata.json", function(data){
var canvas=d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500);
canvas.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("width", function(d){return d.age*10;})
.attr("height", 50)
.attr("fill", "blue")
.attr("y", function(d,i){return i * 60});
canvas.select("text")
.data(data)
.enter()
.append("text")
.attr("fill", "white")
.attr("y", function(d, i){return i * 60})
.text(function(d) {return d.name;});
});
</script>
</body>
</html>
mydata.json
[
{"name": "Maria", "age": 30},
{"name": "Fred", "age": 50},
{"name": "Francis", "age": 12}
]
Running it on a server yields:
app.js
const http=require('http');
const fs=require('fs');
const hostname='127.0.0.1';
const port=3000;
fs.readFile('index.html', (err, html) => {
if (err) {
throw err;
}
const server = http.createServer((req, res) => {
res.statusCode =200;
res.setHeader('Content-type', 'text/html');
res.write(html);
res.end();
});
server.listen(port, hostname, () => {
console.log('Server started on port '+port);
});
});
The persistent error message received is:
Uncaught TypeError: canvas.selectAll(...).data(...).enter is not a function
Switching to D3 version 3 results in the error:
Uncaught TypeError: Cannot read property 'length' of null
Furthermore, attempting to load a .csv file triggers the following error:
Error: attribute width: Expected length, "NaN".