Drawing line and area graphs
Line charts in general
The element
When drawing a line graph, you typically use a path
instead of a line
. A line
is a straight line that goes from one point to another point, while a path
is a line that can change direction.
path
elements
When you’re drawing a line by hand, you draw it on a graph by knowing some x
values and some y
values. path
elements don’t take an x and a y, though, they take something called d
, which is drawing instructions.
<path d="M4,5L4,5 6,5 3,4" stroke="black"></path>
d3.line()
In order to convert our coordinates into something that can go into d
, we use d3.line().
var line = d3.line()
.x(function(d) {
return xPositionScale(d.month);
})
.y(function(d) {
return yPositionScale(d.sales);
});
We then feed that to d
along with our data to draw a line.
If we have a series of values and want to graph it as one line, our code probably looks like this:
// add a single line, attach our data to it
// feed the line generator to d
d3.append("path")
.datum(datapoints)
.attr("d", line);
If we have **multiple lines** we want to draw, we probably first group our data using nest and then do bind/enter/append to draw multiple lines.
// group the data by city name
var nested = d3.nest()
.value(function(d) { d.cityname })
.entries(datapoints);
// add a new line for each city
// and draw a line according to that city's data
d3.selectAll("path")
.data(nested)
.enter().append("path")
.attr("d", function(d) {
return line(d.values);
})
Area charts
Sometimes you fill in the area below the line with color. That’s an area chart!
path
s are also used for shapes, not just lines - to make the path
filled in, we’ll just need to set a fill
instead of a stroke
.
d3.area()
, Part 1
d3.area()
works just like d3.line
(see above), but instead of giving it an x
and a y
you give it an x
, y0
and y1
. The space between the y0
and y1
is what gets filled in.
var area = d3.area()
.x(function(d) {
return xPositionScale(d.month);
})
.y0(0)
.y1(function(d) {
return yPositionScale(d.sales);
});
In the example above, I’m simply coloring in everything between 0 and the number of sales. y0
doesn’t need a function because the lower point of my coloring is going to be 0
every month.
d3.area()
, Part 2
Sometimes you want your area to have a changing bottom, instead of the bottom of the area always being your x axis. Think about a graphic where you’d have a band for high and low temperatures, with a median temperature running through the middle.
In that case you have different y0
and y1
values, so you give them both a function.
var area = d3.area()
.x(function(d) {
return xPositionScale(d.month);
})
.y0(function(d) {
return yPositionScale(d.low)
})
.y1(function(d) {
return yPositionScale(d.high);
});
d3.area()
, Part 3
If you swapped x and y to make your graphic vertical, instead of x
/y0
/y1
, you could set x0
,x1
,y
.