block by nydame 911b76eefa062a988b38

Exercise 6 for Data Visualizations and Infographics with D3

Full Screen

index.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<title>Global Obesity Trends</title>
		<script type="text/javascript" src="//d3js.org/d3.v3.js"></script>
		<style type="text/css">
			body {
				background-color: whitesmoke;
				font-family: 'Raleway', Helvetica, sans-serif;
				font-weight: 300;
			}
			h1 {
				font-weight: 400;
				line-height: 1.5em;
				border-bottom: 1px solid gray;
			}
			svg {
				background-color: mistyrose;
				width: 100%;
			}
			@media screen and (min-width: 768px) {
				svg {
					width: 75%;
				}
			}
			.axis path,
			.axis line {
				fill: none;
				stroke: black;
				shape-rendering: crispEdges;
			}
			.axis text {
				font-family: sans-serif;
				font-size: 11px;
			}
			.y.axis path,
			.y.axis line {
				opacity: 1;
			}
			p {
				font-size: 14px;
				margin: 10px 0;
			}

		</style>
	</head>
	<body>

		<h1>Trends in Obesity by Country</h1>

		<p>Obesity rates for selected OECD countries between 1973 and 2014. (Hover over each line to reveal country name. Data is not available for the entire period for all countries.) Some data were self-reported (dotted lines), whereas others were actually measured (solid lines). Source: <a href="//www.oecd.org/health/health-systems/Fig2-Obesity-rates.xls">OECD.org</a></p>

		<svg id="line-chart" viewBox="0 0 1000 1000" preserveAspectRatio="xMidYMid">
			<!--  -->
		</svg>

		<script type="text/javascript">		
			
			var svg1 = d3.select("svg"),
				h = document.getElementById('line-chart').scrollHeight,
				w = document.getElementById('line-chart').scrollWidth,
				padding = [50, 20, 20, 120],
				yScale = d3.scale.linear().range([ padding[0], h - padding[2] ]),
				xScale = d3.time.scale().range([padding[3], w - padding[1] ]),
				xAxis = d3.svg.axis().scale(xScale).orient("bottom").tickFormat(function(d) {return dateFormat(d);}),
				yAxis = d3.svg.axis().scale(yScale).orient("left").tickFormat(d3.format("%")),
				xOffset = 10,
				yOffset = xOffset;

			//Set up date formatting and years
			var dateFormat = d3.time.format("%Y");



			// //BETTER XSCALE & AXES?
			// var xScale = d3.time.scale()
			// 					.range([ padding[3], w - padding[1] - padding[3] ]);

			//Configure axis generators
			// var xAxis = d3.svg.axis()
			// 				.scale(xScale)
			// 				.orient("bottom")
			// 				.ticks(15)
			// 				.tickFormat(function(d) {
			// 					return dateFormat(d);
			// 				});

			// var yAxis = d3.svg.axis()
			// 				.scale(yScale)
			// 				.orient("left");



			//Configure line generator
			var line = d3.svg.line()
				.x(function(d) {
					return xScale(dateFormat.parse(d.year));
				})
				.y(function(d) {
					return yScale(+d.rate);
				});

			//Load data
			d3.csv("obesity-rates-by-year.csv", function(data) {

				//Data is loaded in, but we need to restructure it.
				//Remember, each line requires an array of x/y pairs;
				//that is, an array of arrays, like so:
				//
				//	[ [x: 1, y: 1], [x: 2, y: 2], [x: 3, y: 3] ]
				//
				//We, however, are using 'year' as x and 'amount' as y.
				//We also need to know which country belongs to each
				//line, so we will build an array of objects that is
				//structured like this:
				/*

					[
						{
							country: "Australia",
							emissions: [
										{ year: 1961, amount: 90589.568 },
										{ year: 1962, amount: 94912.961 },
										{ year: 1963, amount: 101029.517 },
										…
									   ]
						},
						{
							country: "Bermuda",
							emissions: [
										{ year: 1961, amount: 176.016 },
										{ year: 1962, amount: 157.681 },
										{ year: 1963, amount: 150.347 },
										…
									   ]
						},
						…
					 ]

				*/
				//Note that this is an array of objects. Each object
				//contains two values, 'country' and 'emissions'.
				//The 'emissions' value is itself an array, containing
				//more objects, each one holding 'year' and 'amount' values.

				//New array with all the years, for referencing later
				var years = ["1973", "1978", "1987", "1990", "1991", "1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014"];

console.log(data);
				//Create a new, empty array to hold our restructured dataset
				var dataset = [];

				//Loop once for each row in data
				for (var i = 0; i < data.length; i++) {

					//Create new object with this country's name and empty array
					dataset[i] = {
						country: data[i]["Country"],
						dataType: data[i]["Data"],
						obesityRates: []
					};

					//Loop through all the years
					for (var j = 0; j < years.length; j++) {

						// If value is not empty
						if (data[i][years[j]]) {
							//Add a new object to the emissions data array
							//for this country if one exists for this year
							dataset[i]["obesityRates"].push({
								year: years[j],
								rate: data[i][years[j]]
							});
						}

					}

				}
				
console.log(dataset);

				//Set scale domains
				xScale.domain([ 
					d3.min(years, function(d) {
						return dateFormat.parse(d);
					}),
					d3.max(years, function(d) {
						return dateFormat.parse(d);
					})
				]);

				yScale.domain([ 
					d3.max(dataset, function(d) {
						return d3.max(d["obesityRates"], function(e) {
							return +e["rate"];
						});
					}),
					0
				]);



				//Make a group for each country
				var groups = svg1.selectAll("g")
					.data(dataset)
					.enter()
					.append("g")
					.classed("self-reported", function(d) {
						if (d.dataType === "self-reported") {
							return true;
						} else {
							return false;
						}
					});

				//Append a title with the country name (so we get easy tooltips)
				groups.append("title")
					.text(function(d) {
						return d.country;
					});

				//Within each group, create a new line/path,
				//binding the obesity rate data to each one
				groups.selectAll("path")
					.data(function(d) {
						return [ d.obesityRates ];
					})
					.enter()
					.append("path")
					.attr("class", "line")
					.attr("d", line)
					.attr("fill", "none")
					.attr("stroke", "gray")
					.attr("stroke-width", 2);

				// Make lines from self-reported data dashed
				d3.selectAll(".self-reported path")
					.attr("stroke-dasharray", "5,5");

				//Axes
				svg1.append("g")
					.attr("class", "x axis")
					.attr("transform", "translate(0," + (h - padding[2]) + ")")
					.call(xAxis);

				svg1.append("g")
					.attr("class", "y axis")
					.attr("transform", "translate(" + (padding[3]) + ",0)")
					.call(yAxis);

			});

		</script>

	</body>
</html>

obesity-rates-by-year.csv

Country,Data,1973,1978,1987,1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014
United States,measured,0.1372920797,0.1536677972,,,0.2181977146,,,,,,,,0.2937643484,,0.2940559119,,0.3125682329,,0.3314561096,,0.3240610504,,0.3457215378,,0.3443611119,,,
Canada,self-reported,,,,,,,,,0.1365326861,,,,,,,,0.1595444607,,0.1679761279,,0.17924919,,0.1888175504,,0.1923309785,,,
Mexico,measured,,,,,,,,,,,,,,0.2819796396,,,,,,0.3051071691,,,,,,0.3289594364,,
Spain,self-reported,,,0.097575,,,,0.090487,,0.110525,,0.119818,,,,0.12003,,0.12143,,,0.138948,,,0.140604,,0.1522178198,,,
France,self-reported,,,,0.061681,0.060188,0.066347,0.066248,0.071629,0.070605,0.087637,0.077696,0.084232,,0.090114,,0.090777,,0.098537,,0.10743,,0.111651,,0.122403,,,,
Italy,self-reported,,,,,,,,,0.068203,,,,,0.083112,,,,,0.086724,0.0875604861,0.0848055899,0.0828324437,0.0861655199,0.0860337329,0.0833290314,0.0862485294,,
England,measured,,,,,0.142716,0.144369,0.14516,0.151147,0.15887,0.167192,0.176034,0.183015,0.190308,0.200086,0.212824,0.2146687562,0.2158770704,0.2210202756,0.2234572976,0.2285242412,0.2271382578,0.2338699502,0.2175313457,0.2487609527,0.2327842658,,,
Switzerland,self-reported,,,,,,0.050836,,,,,0.062105,,,,,0.07183,,,,,0.075202,,,,,0.090458,,
Korea,measured,,,,,,,,,,,,0.02367,,,0.03165,,,,0.033893,,,0.037455,,,0.0437718291,,,
Australia,measured,,,,,,,,,0.1820782099,,,,,,,,,,,,,0.2374963855,,,,0.2632963039,,