How to make a Line Chart in D3
Basic Line 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(d.date); })
.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.
svg.append("path")
.datum(data)
.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>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
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;
}
</style>
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js" 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()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.death); })
.interpolate("basis");
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("deathrates.csv?1", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.Year); //parseDate(d.Year);
d.death = +d["Crude death rate (per 1,000)"];
});
console.log(data);
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.death; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Death Rate");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line)
.style({"stroke":"steelblue", "stroke-width":"1.5px", "fill":"none"});
});
</script>
</body>
</html>