1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
// Fetch the JSON data
d3.json("data.json").then(function(data) {
// Set the dimensions and margins of the chart
var margin = {top: 20, right: 30, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
// Append the SVG object to the chart div
var svg = d3.select("#chart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// X scale and axis
var x = d3.scaleLinear()
.domain([0, d3.max(data, function(d) { return d.x; })])
.range([0, width]);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Y scale and axis
var y = d3.scaleLinear()
.domain([0, d3.max(data, function(d) { return d.y; })])
.range([height, 0]);
svg.append("g")
.call(d3.axisLeft(y));
// Create a line generator
var line = d3.line()
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); });
// Add the line to the chart
svg.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 2)
.attr("d", line);
});
|