How to make a Line Chart in D3

Basic Line Chart

A basic bar chart

Prepare your data as a CSV file

Make sure your data are real numbers, and have no commas or symbols in them (decimals are OK).

Save your spreadsheet as a .csv file in a folder where you will put the html for your bar chart.

Difference from Bar Chart

The biggest difference in creating a line chart is using the line function in D3.

var line = d3.svg.line()
    .x(function(d) { return x(; })
    .y(function(d) { return y(d.death); })
    .interpolate("basis"); //optional, for smoother lines

This function takes the x and y scale datea x() and y() and it will automatically compute a line. In your chart, you will call this line function as the value of the d attribute of the <path> element.

    .attr("class", "line")
    .attr("d", line); //we apply the line variable, which we determined earlier

The result will be a path element that is drawn appropriately.

Example of a line chart

<!DOCTYPE html>
    <meta charset="utf-8">

    body {
      font: 10px sans-serif;

    .axis path,
    .axis line {
      fill: none;
      stroke: #000;
      shape-rendering: crispEdges;

    .x.axis path {

    .line {
      fill: none;
      stroke: steelblue;
      stroke-width: 1.5px;


    <script src="" charset="utf-8"></script>
    <script type="text/javascript">

    var margin = {top:50, right:0, bottom:70, left:70},
        width  = 900,
        height = 600;

    var parseDate = d3.time.format("%Y").parse;

    var x = d3.time.scale()
        .range([0, width]);

    var y = d3.scale.linear()
        .range([height, 0]);

    var xAxis = d3.svg.axis()

    var yAxis = d3.svg.axis()

    var line = d3.svg.line()
        .x(function(d) { return x(; })
        .y(function(d) { return y(d.death); })

    var svg ="body").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + + margin.bottom)
        .attr("transform", "translate(" + margin.left + "," + + ")");

    d3.csv("deathrates.csv?1", function(error, data) {
      data.forEach(function(d) {
        = parseDate(d.Year); //parseDate(d.Year);
        d.death = +d["Crude death rate (per 1,000)"];


      x.domain(d3.extent(data, function(d) { return; }));
      y.domain(d3.extent(data, function(d) { return d.death; }));

          .attr("class", "x axis")
          .attr("transform", "translate(0," + height + ")")

          .attr("class", "y axis")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .style("text-anchor", "end")
          .text("Death Rate");

        .attr("class", "line")
        .attr("d", line)
        .style({"stroke":"steelblue", "stroke-width":"1.5px", "fill":"none"});