SimpleD3LinePlot

by Simon Raper

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<div id="chart_container">
    <div id="time_series_chart"></div>
    <div id="side_panel"></div>
</div>

CSS

#chart_container {
    width: 800px;
    height: 250px;
}
#side_panel {
    width: 180px;
    height: 160px;
    float: left;
    padding: 20px;
}
#time_series_chart {
    width: 580px;
    height: 250px;
    float: left;
}
.axis {
    font: 10px sans-serif;
}
.axis path, .axis line {
    fill: none;
    stroke: #000;
    shape-rendering: crispEdges;
}
.line {
    fill: none;
    stroke: steelblue;
    stroke-width: 1.5px;
}

JavaScript

//Set up the layout variables

var margin = {
    top: 30,
    right: 20,
    bottom: 30,
    left: 50
};
var svg_width = 650,
    svg_height = 250;

var mindate = new Date(2012, 2, 19),
    maxdate = new Date(2012, 2, 26);

//Set up color scales
var color = d3.scale.category10();

//Add the data 
data = [{
    "name": "turnips",
        "values": [{
        "date": "2012-03-20",
            "total": 30
    }, {
        "date": "2012-03-21",
            "total": 8
    }, {
        "date": "2012-03-22",
            "total": 2
    }, {
        "date": "2012-03-23",
            "total": 10
    }, {
        "date": "2012-03-24",
            "total": 3
    }, {
        "date": "2012-03-25",
            "total": 20
    }, {
        "date": "2012-03-26",
            "total": 12
    }]
}, {
    "name": "carrots",
        "values": [{
        "date": "2012-03-20",
            "total": 4
    }, {
        "date": "2012-03-21",
            "total": 2
    }, {
        "date": "2012-03-22",
            "total": 5
    }, {
        "date": "2012-03-23",
            "total": 11
    }, {
        "date": "2012-03-24",
            "total": 3
    }, {
        "date": "2012-03-25",
            "total": 16
    }, {
        "date": "2012-03-26",
            "total": 12
    }]
}];

//Set up date parser
var parse_date = d3.time.format("%Y-%m-%d").parse;

//Parse the dates
data.forEach(function (d) {
    d.values.forEach(function (e) {
        e.date = parse_date(e.date);
    })
});


//Add the svg
var svg = d3.select("#time_series_chart")
    .append("svg")
    .attr("width", svg_width)
    .attr("height", svg_height);

//Create some axes
var x_scale = d3.time.scale()
    .domain([mindate, maxdate])
    .range([0, svg_width - margin.right - margin.left]);

var y_scale = d3.scale.linear()
    .domain([0, 100])
    .range([svg_height - margin.top - margin.bottom, 0]);

var x_axis = d3.svg.axis()
    .scale(x_scale)
    .orient('bottom')
    .ticks(5);

var y_axis = d3.svg.axis()
   ...