Skip to content

Instantly share code, notes, and snippets.

@humberto-ortiz
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save humberto-ortiz/9864410 to your computer and use it in GitHub Desktop.
Save humberto-ortiz/9864410 to your computer and use it in GitHub Desktop.
Simple line chart for SalHUD

Gist for a simple line chart for public health data from Puerto Rico.

Humberto Ortiz-Zuazaga humberto.ortiz@upr.edu

Part of SalHUD.

2014/03/31 - HOZ

Added x axis line, fixed labels.

2014/03/30 - HOZ

Added a second line and modified the date format from the example:

http://bl.ocks.org/mbostock/3883245

date raw adj
2000 756.3 850.5
2001 767.1 846.2
2002 736.5 797.9
2003 744.0 790.7
2004 760.2 791.5
2005 766.6 779.2
2006 729.3 723.4
2007 744.0 719.8
2008 735.9 694.6
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.line {
fill: none;
stroke: green;
stroke-width: 1.5px;
}
.line2 {
fill: none;
stroke: blue;
stroke-width: 1.5px;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.js"></script>
<script>
var margin = {top: 20, right: 20, bottom: 50, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
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.adj); });
var line2 = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.raw); });
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("chart.csv", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.raw = +d.raw;
d.adj = +d.adj;
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.adj; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("x", width / 2)
.style("text-anchor", "middle")
.attr("y", 40)
.text("Año");
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("y", -30)
.attr("x", -(height / 2))
.attr("dy", ".71em")
.style("text-anchor", "end")
.attr("transform", "rotate(-90)")
.text("Tasa");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
svg.append("path")
.datum(data)
.attr("class", "line2")
.attr("d", line2);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment