Line Graph with Legend

Posted .

Creating a simple line graph using D3 is pretty easy, after doing a Basic Setup we just have to add a path and possibly a legend.

Here is the source of the final graph.

Path

There are two steps to adding a path element for a line graph. First we define a line function, this function creates the content of the d attribute (which defines the shape of a path element) from data. (Note how we use the x() and y() scale functions we defined earlier.) The d parameter of the anonymous function below will refer to a single datapoint of the data.

let line = d3.line()
  .x(d => x(d.date))
  .y(d => y(d.temperature))

Then we add a path and set the appropriate attributes.

svg.append("path")
  .attr("d", line(data))
  .attr("stroke", "steelblue")
  .attr("stroke-linejoin", "round")
  .attr("fill", "none")

The result is a simple line graph, see fig. 1.

JanFebMarAprMayJunJulAugSepOctNovDecJanDate35404550556065707580Temperature (F°)

We can repeatedly append paths to add additional lines but then we need a legend as well.

Legend

We start by adding a group element and use it to move the legend into the right position and set the font size. The legend here is moved to the top right corner of the graph, the 80 is the width of the legend.

let legend = svg.append("g")
  .attr("transform",
    `translate(${width - margin.right - 80}, ${margin.top})`
  )
  .style("font-size", "12px")

Then we can add <text> and <line> elements in a such a way to create a legend.

legend.append("text")
  .attr("y", 4)
  .attr("x", "22")
  .text("Maximum")
legend.append("line")
  .attr("x1", 0).attr("y1", 0)
  .attr("x2", 18).attr("y2", 0)
  .attr("stroke", "maroon")

These were repeated, with 12 added to the y coordinates each time, to add the other lines of the legend. The result is a line graph with a legend, see fig. 2.

JanFebMarAprMayJunJulAugSepOctNovDecJanDate35404550556065707580Temperature (F°)MaximumAverageMinimum