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.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">

    <script src=""></script>
    <script type="text/javascript">

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

    // parse the date / time
    var parseDate = d3.timeParse("%Y");

    //Note: If your x scale is not time data, then you'll want to use
    // d3.scalePoint() instead for your x variable below

    //set the scales based on time
    var x = d3.scaleTime().range([0, width]);
    var y = d3.scaleLinear().range([height, 0]);

    var line = d3.line()
        .x(function(d) { return x(; })
        .y(function(d) { return y(d.death); })
        //For examples of different curve styles, see:
    var svg ="body")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + + margin.bottom);
    var chart = svg.append("g")
        .attr("transform", "translate(" + margin.left + "," + + ")");

    d3.csv("deathrates.csv", function(error, data) {
        if (error) throw error;
        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(" + margin.left + "," + (height + + ")")

            .attr("transform", "translate(" + margin.left + "," + + ")")
            .attr("transform", "rotate(-90)")
            .attr("y", 6)
            .attr("dy", ".71em")
            .style("text-anchor", "end")
            .text("Death Rate");

            .attr("class", "line")
            .attr("d", line)