Import D3

1
<script src="https://d3js.org/d3.v4.min.js"></script>

Code

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// set size
const margin = {
top: 50,
right: 50,
bottom: 50,
left: 50,
}
const width = window.innerWidth - margin.left - margin.right
const height = window.innerHeight - margin.top - margin.bottom

// Set Point Number
const n = 21

// X scale will use the index of our data
const xScale = d3.scaleLinear()
.domain([0, n-1]) // input
.range([0, width]) // output

// Y scale will use the randomly generated number
const yScale = d3.scaleLinear()
.domain([0, 1]) // input
.range([height, 0]) // output

// d3's line generator
const line = d3.line()
.x(function(d, i) {
return xScale(i) // set the x value for the line generator
})
.y(function(d, i) {
return d.y // set the y value for the line generator
})
.curve(d3.curveMonotoneX) // apply smoothing to the line

const dataset = d3.range(n)
.map(function(d) {
return {
y: d3.randomUniform(1)()
}
})

// Add SVG to the page
const svg = d3.select('body')
.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})`)

// Call the X axis in a group tag
svg.append('g')
.attr('class', 'x axis')
.attr('transform', `translate(0, ${height})`)
.call(d3.axisBottom(xScale)) // Create an axis component with d3.axisBottom

// Call the Y axis in a group tag
svg.append('g')
.attr('class', 'y axis')
.call(d3.axisLeft(yScale))

// Append the path, bind the data, and call the line generator
svg.append('path')
.datum(dataset) // bind data to the path
.attr('class', 'line')
.attr('d', line) // call the line generator

// Append a circle for each data point
svg.selectAll('.dot')
.data(dataset)
.enter().append('circle')
.attr('cx', function (d, i) {
return xScale(i)
})
.attr('cy', function (d, i) {
return yScale(dy)
})
.attr('r', 5)

Add style

1
2
3
4
5
6
7
8
9
.line {
fill: none;
stroke: cyan;
storke-width: 3;
}
.dot {
fill: #ffab00;
stroke: #FFF;
}