This dataset is about the leading causes of death by sex and ethnicity in New York City in since 2007, the raw json file can be found here.
More about this theme click this link.
This line chart presents the top 5 causes of death each year.
Chart code forked from d3noob’s block. Inspired by click this link
xxxxxxxxxx
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://d3js.org/d3.v4.min.js"></script>
<title>New York City Leading Causes of Death</title>
<style>
body { font: 12px Arial;}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
.legend {
font-size: 10px;
font-weight: bold;
text-anchor: middle;
}
</style>
</head>
<body>
<script>
var margin = {top: 30, right: 20, bottom: 70, left: 50},
width = 800 - margin.left - margin.right,
height = 480 - margin.top - margin.bottom;
var parseDate = d3.timeParse("%Y");
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
var priceline = d3.line()
.x(function(d) { return x(d.Year); })
.y(function(d) { return y(d.Deaths); });
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("NY_data.csv", function(error, data) {
data.forEach(function(d) {
d.Year = parseDate(d.Year);
d.Deaths = +d.Deaths;
});
x.domain(d3.extent(data, function(d) { return d.Year; }));
y.domain([0, d3.max(data, function(d) { return d.Deaths; })]);
var dataNest = d3.nest()
.key(function(d) {return d.Cause;})
.entries(data);
var color = d3.scaleOrdinal(d3.schemeCategory10);
legendSpace = width/dataNest.length;
dataNest.forEach(function(d,i) {
svg.append("path")
.attr("class", "line")
.style("stroke", function() {
return d.color = color(d.key); })
.attr("id", 'tag'+d.key.replace(/\s+/g, ''))
.attr("d", priceline(d.values));
svg.append("text")
.attr("x", (legendSpace/2)+i*legendSpace)
.attr("y", height + (margin.bottom/2)+ 5)
.attr("class", "legend")
.style("fill", function() {
return d.color = color(d.key); })
.on("click", function(){
var active = d.active ? false : true,
newOpacity = active ? 0 : 1;
d3.select("#tag"+d.key.replace(/\s+/g, ''))
.transition().duration(100)
.style("opacity", newOpacity);
d.active = active;
})
.text(d.key);
});
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
svg.append("g")
.attr("class", "axis")
.call(d3.axisLeft(y));
});
</script>
</body>
</html>
https://d3js.org/d3.v4.min.js