I'm struggling with understanding the correct structure for writing D3 code.
For example: In the code snippet below, I noticed that if I place the 3rd section (Chart Title) of the code after creating the svg element, the title text doesn't display. However, if I mention the 3rd section before creating the svg, the chart works as expected.
Why is that?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
circle.dimple-series-1{
fill: red;
}
h2{
color: black;
text-align: center;
font-family: monospace;
font-size: 20px;
}
</style>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://dimplejs.org/dist/dimple.v2.0.0.min.js"></script>
<script type="text/javascript">
function draw(data) {
/*
Setting up D3.js
*/
"use strict";
var margin = 75,
width = 1400 - margin,
height = 600 - margin;
/*Adding TITLE*/
d3.select("body")
.append("h2").text("Goals by Year!");
/*Creating SVG Element*/
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin)
.attr("height", height + margin)
.append('g')
.attr('class','chart');
/*
Constructing Dimple.js Chart
*/
var myChart = new dimple.chart(svg, data);
var x = myChart.addTimeAxis("x", "year");
x.dateParseFormat="%Y"
x.tickFormat="%Y";
x.timeInterval= 4;
myChart.addMeasureAxis("y", "attendance");
myChart.addSeries(null, dimple.plot.line);
myChart.addSeries(null, dimple.plot.scatter);
myChart.draw();
};
</script>
</head>
<body>
<script type="text/javascript">
/*
Using D3 to load the TSV file
and passing the data to the draw function
*/
d3.tsv("world_cup.tsv", draw);
</script>
</body>
</html>