12 Line charts
Read: IDVW2, Chapter 11 Using Paths
12.1 SVG <line>
element
(Use for two points only.)
<line x1="50" y1="180" x2="400" y2="20" stroke="blue" stroke-width="5"></line>
12.2 SVG <path>
element
(Use if you have more than two points.)
<path d="M 50 200 L 100 100 L 150 100 L 200 33 L 250 175
L 300 275 L 350 250 L 400 125" fill="none"
stroke="red" stroke-width="5"></path>
d
attribute: M = move to, L = line to
More options: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/d
12.3 Data for line chart
Format that we have:
Day | High Temp |
---|---|
April 1 | 60 |
April 2 | 43 |
April 3 | 43 |
April 4 | 56 |
April 5 | 45 |
April 6 | 62 |
April 7 | 49 |
To create a line chart we need to generate the d
attribute.
12.4 Create a line generator
Expects data in an array of 2-dimensional arrays, that is, an array of (x,y) pairs:
const dataset = [ [0, 60], [1, 43], [2, 43], [3, 56], [4, 45], [5, 62], [6, 49] ];
const mylinegen = d3.line()
Test it in the Console:
mylinegen(dataset);
Add an ordinal scale for x:
const xScale = d3.scaleBand()
.domain(d3.range(dataset.length))
.range([0, 500])
… and a linear scale for y:
const yScale = d3.scaleLinear()
.domain([d3.min(dataset, d => d[1]) - 20,
.max(dataset, d => d[1]) + 20])
d3.range([400, 0]);
*Why d[1]
instead of d
? (See p. 122)
Add accessor functions .x()
and .y()
:
mylinegen.x(d => xScale(d[0]))
.y(d => yScale(d[1]));
Test again:
mylinegen(dataset);
Now let’s add a <path>
element with that d
attribute: (this step is just for learning purposes…)
const mypath = mylinegen(dataset);
.select("svg#mypath")
d3.append("path").attr("d", mypath)
.attr("fill", "none").attr("stroke", "red")
.attr("stroke-width", "5");
12.5 Put the line generator to work
The more common (and direct) method to create a path: bind the datum and calculate the path in one step:
.select("svg").append("path")
d3.datum(dataset)
.attr("d", mylinegen) // passes the data to mylinegen
.attr("fill", "none")
.attr("stroke", "teal")
.attr("stroke-width", "5");
Finally, we’ll add a class and style definitions:
<style>
.linestyle {
fill: none;
teal;
stroke: 5px;
stroke-width:
}</style>
The append("path")
line becomes:
.append("path")
svg.datum(dataset)
.attr("d", mylinegen)
.attr("class", "linestyle");
And another example with axes:
(Also uses: d3.timeParse()
and JavaScript Array.foreach()
)
12.6 Additional Resources
Multiple Time Series in D3 by Eric Boxer (EDAV 2018)