<|start_filename|>code/styles.css<|end_filename|>
.image {
	height: 200px;
	position: relative;
	left: 20px;
}


<|start_filename|>code/main09.js<|end_filename|>
// Load the data.
var dataUrl = "https://raw.githubusercontent.com/IsaKiko/D3-visualising-data/gh-pages/code/nations.json";
d3.json(dataUrl, function(nations) {

	var filtered_nations = nations.map(function(nation) { return nation; });

	// Create the SVG frame inside chart_area.
	var chart_area = d3.select("#chart_area");
	var frame = chart_area.append("svg");

	// Create canvas inside frame.
	var canvas = frame.append("g");

	// Set margins, width, and height.
	var margin = {top: 19.5, right: 19.5, bottom: 19.5, left: 39.5};
	var frame_width = 960;
	var frame_height = 350;
	var canvas_width = frame_width - margin.left - margin.right;
	var canvas_height = frame_height - margin.top - margin.bottom;


	// Set svg attributes width and height.
	frame.attr("width", frame_width);
	frame.attr("height", frame_height);


	// Shift the chart and make it slightly smaller than the svg canvas.
	canvas.attr("transform", "translate(" + margin.left + "," + margin.top + ")");


  // Various scales. These domains make assumptions of data, naturally.
  var xScale = d3.scaleLog(); // income
  xScale.domain([250, 1e5]);
  xScale.range([0, canvas_width]);

  // d3 has a subobject called scale. within scale, there are a number of functions to create scales.
  // e.g. scaleLog, scaleLinear, scaleSqrt, d3.schemeCategory20 (e.g. 20 different colours)...
  // we set the domain based on our data - min and max of the data
  // we set the range - range on the page
  // domain, range, log scale all determing data values are mapped to graph positions.

  var yScale = d3.scaleLinear().domain([10, 85]).range([canvas_height, 0]);  // life expectancy
  var colorScale = d3.scaleOrdinal(d3.schemeCategory20);

  // an alternative notation that d3 offers is to chain everything together using the dot-syntax
  // (you'll see this a lot). The order is mostly arbitrary.

  // Creating the x & y axes.
  var xAxis = d3.axisBottom(xScale);
  var yAxis = d3.axisLeft(yScale);

  var rScale = d3.scaleSqrt().domain([0, 5e8]).range([0, 40]); // life expectancy


    // Next step: push the axes into the chart
	// Add the x-axis.
	canvas.append("g")
	.attr("class", "x axis")
    .attr("transform", "translate(0," + canvas_height + ")")
    .call(xAxis);

    // .call is the bit where the properties we just set are pushed to the object
    // attribures are added to make it look pretty (class is used in the css file)


	// Add the y-axis.
	canvas.append("g")
    .attr("class", "y axis")
    .call(yAxis);



	//////////////////////AXES CREATED//////////////////////////



	//////////////////////FILL IN DATA//////////////////////////


	// var filtered_nations = nations.filter(function(nation){ return nation.population[nation.population.length-1][1] > 10000000;});

	// var filtered_nations = nations.filter(function(nation){ return nation.region == "Sub-Saharan Africa";});

	var data_canvas = canvas.append("g")
  	.attr("class", "data_canvas");

	update();

	// dot is finding a class, hash an ID

	// check boxes
	d3.selectAll(".region_cb").on("change", function() {
		var type = this.value;
		if (this.checked) { // adding data points (not quite right yet)
			var new_nations = nations.filter(function(nation){ return nation.region == type;});
			filtered_nations = filtered_nations.concat(new_nations);
		} else { // remove data points from the data that match the filter
			filtered_nations = filtered_nations.filter(function(nation){ return nation.region != type;});
		}
		update();
	});

	// update the plot, includes enter, exit, and transition
  function update() {
    var dot = data_canvas.selectAll(".dot")
    .data(filtered_nations, function(d){return d.name});

    dot.enter().append("circle").attr("class","dot")
                  .style("fill", function(d) { return colorScale(d.region); })
                  .attr("cx", function(d) { return xScale(d.income[d.income.length-1]); }) // this is how attr knows to work with the data
                  .attr("cy", function(d) { return yScale(d.lifeExpectancy[d.lifeExpectancy.length-1]); })
                  .attr("r", function(d) { return rScale(d.population[d.population.length-1]); });

    dot.exit().remove();
  }

})

<|start_filename|>resources/interpolateDataScript.js<|end_filename|>
var fs = require('fs');
var args = process.argv.slice(2);

var years = [];
for (var year = 1950; year <= 2008; year++) {
	years.push(year);
}

function interpolateYears(array, years) {
	var out = [];
	var j = 0; // index into 'years'
	for (var i = 0; i < array.length; i++) {
		if (j >= years.length) {
			return out;
		}
		while (array[i][0] > years[j]) {
			if (i == 0) {
				// console.log('Warning: No data as early as ' + years[j] + '.');
				return [];
			}
			var fraction = (years[j] - array[i-1][0])/(array[i][0] - array[i-1][0]);
			var interpolatedValue = array[i-1][1] + (array[i][1] - array[i-1][1])*fraction;
			out.push(interpolatedValue);
			j += 1;
		}
		if (array[i][0] == years[j]) {
			out.push(array[i][1]);
			j += 1;
		}
	}
	return out;
}

var data = JSON.parse(fs.readFileSync(args[0]));
var processedData = data.map(function(nation) {
	var processedNation = {
		name: nation.name,
		region: nation.region,
		years: years,
		income: interpolateYears(nation.income, years),
		population: interpolateYears(nation.population, years),
		lifeExpectancy: interpolateYears(nation.lifeExpectancy, years)
	};
	var excludeNation = false;
	excludeNation = excludeNation || (processedNation.income.length != years.length);
	excludeNation = excludeNation || (processedNation.population.length != years.length);
	excludeNation = excludeNation || (processedNation.lifeExpectancy.length != years.length);
	if (excludeNation) {
		console.log('Excluding "' + nation.name + '" because of lack of data.');
		// console.log(years.length);
		// console.log(processedNation.income.length);
		// console.log(processedNation.population.length);
		// console.log(processedNation.lifeExpectancy.length);
		return undefined;
	} else {
		return processedNation;
	}
}).filter(function(nation) {
	return nation != undefined;
});

fs.writeFileSync(args[1], JSON.stringify(processedData, undefined, 2));


<|start_filename|>code/main.css<|end_filename|>

text {
  font: 10px sans-serif;
}

.dot {
  stroke: #000;
}

.label {
  fill: #777;
}

.year.label {
  font: 500 196px "Helvetica Neue";
  fill: #ddd;
}

.year.label.active {
  fill: #aaa;
}

.overlay {
  fill: none;
  pointer-events: all;
  cursor: ew-resize;
}


<|start_filename|>07-d3setup.html<|end_filename|>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="generator" content="pandoc">
    <title>Software Carpentry: D3 setup</title>
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-theme.css" />
    <link rel="stylesheet" type="text/css" href="css/swc.css" />
    <link rel="alternate" type="application/rss+xml" title="Software Carpentry Blog" href="http://software-carpentry.org/feed.xml"/>
    <meta charset="UTF-8" />
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>
  <body class="lesson">
    <div class="container card">
      <div class="banner">
        <a href="http://software-carpentry.org" title="Software Carpentry">
          <img alt="Software Carpentry banner" src="img/software-carpentry-banner.png" />
        </a>
      </div>
      <div class="row">
        <div class="col-md-10 col-md-offset-1">
          <h1 class="title">D3 setup</h1>
          <h2 class="subtitle">Setting up html for our data visualisation</h2>
<div id="learning-objectives" class="objectives panel panel-warning">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-certificate"></span>Learning Objectives</h2>
</div>
<div class="panel-body">
<ul>
<li>Setting up an html file to contain the plot</li>
<li>Reading in data from a given <code>.json</code> file</li>
<li>Structuring the html content</li>
</ul>
</div>
</div>
<p>We've finally learned everything we need to know to start using D3. D3 is a JavaScript library. This means that we can use all of the JavaScript commands that we have already learned, but on top of these, there are a few new functions that will make our life easier.</p>
<p>The main purpose of D3 is to create visualisations of data online. Because it uses JavaScript, it is possible to make graphs interactive!</p>
<p>As a little refresher, we will repeat a little bit html to set up our page.</p>
<p>Create a new GitHub repository and create a gh-pages branch to which you commit. This is, where our actual page will live. Then create <code>index.html</code> in the new repository containing the following:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="dt">&lt;!DOCTYPE </span>html<span class="dt">&gt;</span>
<span class="kw">&lt;html&gt;</span>
  <span class="kw">&lt;head&gt;</span>
    <span class="kw">&lt;title&gt;</span>The Wealth <span class="er">&amp;</span> Health of Nations<span class="kw">&lt;/title&gt;</span>
    <span class="kw">&lt;link</span><span class="ot"> rel=</span><span class="st">&quot;stylesheet&quot;</span><span class="ot"> type=</span><span class="st">&quot;text/css&quot;</span><span class="ot"> href=</span><span class="st">&quot;main.css&quot;</span> <span class="kw">/&gt;</span>
  <span class="kw">&lt;/head&gt;</span>
  <span class="kw">&lt;body&gt;</span>

    <span class="kw">&lt;h1&gt;</span>The Wealth <span class="er">&amp;</span> Health of Nations<span class="kw">&lt;/h1&gt;</span>

    <span class="kw">&lt;p</span><span class="ot"> id=</span><span class="st">&quot;chart_area&quot;</span><span class="kw">&gt;&lt;/p&gt;</span>

    <span class="kw">&lt;script</span><span class="ot"> src=</span><span class="st">&quot;http://d3js.org/d3.v3.min.js&quot;</span><span class="kw">&gt;&lt;/script&gt;</span>
    <span class="kw">&lt;script</span><span class="ot"> src=</span><span class="st">&quot;main.js&quot;</span><span class="kw">&gt;&lt;/script&gt;</span>
  <span class="kw">&lt;/body&gt;</span>
<span class="kw">&lt;/html&gt;</span></code></pre>
<p>There are a few things in this file that look new: <code>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;main.css&quot; /&gt;</code> is linking the local CSS file <code>main.css</code>(that can just be an empty file for now). <code>&lt;script src=&quot;main.js&quot;&gt;&lt;/script&gt;</code> is linking the JavaScript file, the file in which all the action will happen.</p>
<p>Additionally, we now need to link d3 using <code>&lt;script src=&quot;http://d3js.org/d3.v3.min.js&quot;&gt;&lt;/script&gt;</code>. The order matters. Since code is executed sequentially and we want to use parts of the D3 library in our own script, we have to link to d3.js first.</p>
<p>The last bit, that's important here is an HTML element (paragraph) we create. We give it an id <code>chart_area</code>. This is the area we reserve for our pretty chart. We will use JavaScript (and D3) to fill it in.</p>
<p>Now, let's write main.js.</p>
<p>Similar to the syntax we've already seen (<code>JSON.stringify</code>), D3-specific functions can be called using a <code>d3.</code>-syntax.</p>

<p>The first thing we need, is of course our data, which we can find at <a href="https://raw.githubusercontent.com/IsaKiko/D3-visualising-data/gh-pages/code/nations.json">https://raw.githubusercontent.com/IsaKiko/D3-visualising-data/gh-pages/code/nations.json</a>. D3 provides a handy function to read in <code>json</code>-files:
<pre class="d3"><code>var dataUrl = &quot;https://raw.githubusercontent.com/IsaKiko/D3-visualising-data/gh-pages/code/nations.json&quot;;
d3.json(dataUrl, function(nations) { })</code></pre>
<p>This line probably needs a little explanation and we'll go through it bit by bit:</p>
<ul>
<li><code>d3.json()</code> is called the function call. In this case, we have a function that reads in a json file, parses it, and is also able to do something with the parsed data on the way.</li>
<li>The first argument <code>dataUrl</code> tells the function where to get the data we want to have parsed.</li>
<li><code>function(...){...}</code> is called the callback function. It is a so-called 'inline' function, which means it has no name (we're only operating in the object space here). This also means we can't use this function anywhere else in our code. The code we put inside the curly brackets is the code that's run once d3.json() is called and the data is loaded.</li>
<li>D3 assigns the name <code>nations</code> to the parsed object it returns. We can only use 'nations' within the callback function, this means our code only knows of <code>nations</code> inside the curly brackets.</li>
<li>What seems unusual, but is actually quite common, is that this function call doesn't return anything. It is simply executed and displayed (if we tell it to), but no value is returned.</li>
</ul>
<div id="what-else-can-i-read-in-conveniently" class="callout panel panel-info">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pushpin"></span>What else can I read in conveniently?</h2>
</div>
<div class="panel-body">
<p>D3 offers the possibility to also read in csv (comma-separated values) files directly. See <a href="https://github.com/mbostock/d3/wiki/CSV">here</a> for an example. Also available are functions to read in tab-separated values (tsv) and files with arbitrary delimiter (dsv).</p>
</div>
</div>
<p>So naturally, the next step is to think about what we want to happen between the curly brackets. For now, we want to:</p>
<ul>
<li>Link JavaScript to HTML page</li>
<li>Insert an SVG canvas</li>
<li>Create axes (x: income per capita, y: life expectancy)</li>
<li>Display data points (scatter plot)</li>
</ul>
<p>First, let's draw a little schematic of how we want the page to be structured.</p>
<p><img src="img/chart_area.png" alt="What we want.." width="700" /></p>
<p>We already set up our HTML page to contain a chart area. That's the space we want to fill now. We'll have a picture frame (an SVG-element), our drawing area (a g-element), and in that drawing area, we'll have separate elements for both axes and the area for our circles.</p>
<p>What we now want to end up with in our html document is this:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;p</span><span class="ot"> id=</span><span class="st">&quot;chart_area&quot;</span><span class="kw">&gt;</span> <span class="kw">&lt;svg&gt;</span> <span class="kw">&lt;/svg&gt;</span> <span class="kw">&lt;/p&gt;</span></code></pre>
<p>But this time, we want to create these elements automatically using JavaScript only. First, we need to link the JavaScript and HTML environment so that we have writing access to the HTML. To do this, we use the <code>.select()</code>. This lets us grab an element by specifying its ID.</p>
<pre class="js"><code>// Select the chart area by ID
var chart_area = d3.select(&quot;#chart_area&quot;);</code></pre>
<p>Now we're setting up the grid by appending the chart area by the SVG picture frame.</p>
<pre class="js"><code>var frame = chart_area.append(&quot;svg&quot;);</code></pre>
<p>in the HTML file. We chose to append because we now have access to the SVG element without the need to seperately select it by ID.</p>
<p>We also create the canvas inside the frame:</p>
<pre class="js"><code>// Create canvas inside frame.
var canvas = frame.append(&quot;g&quot;);</code></pre>
<p>Let's set up the dimensions for our elements that we want to use:</p>
<pre class="js"><code>// Set margins, width, and height.
var margin = {top: 19.5, right: 19.5, bottom: 19.5, left: 39.5};
var frame_width = 960;
var frame_height = 350;
var canvas_width = frame_width - margin.left - margin.right;
var canvas_height = frame_height - margin.top - margin.bottom;</code></pre>
<p>...and apply them to the actual elements:</p>
<pre class="js"><code>// Set frame attributes width and height.
frame.attr(&quot;width&quot;, frame_width);
frame.attr(&quot;height&quot;, frame_height);</code></pre>
<p>The canvas element will have to fit nicely into the frame. To make it fit, we set a transform attribute and use the translate function.</p>
<pre class="js"><code>// Shift the canvas and make it slightly smaller than the svg canvas.
canvas.attr(&quot;transform&quot;, &quot;translate(&quot; + margin.left + &quot;,&quot; + margin.top + &quot;)&quot;);</code></pre>
<div id="adding-svgs-from-javascript-file" class="challenge panel panel-success">
<div class="panel-heading">
<h1><span class="glyphicon glyphicon-pencil"></span>Adding SVGs from JavaScript file</h1>
</div>
<div class="panel-body">
<ol style="list-style-type: decimal">
<li>Add a SVG circle element to the frame.</li>
<li>Once the circle reference is obtained, make the radius 40px, the border black and the colour green.</li>
</ol>
<p>HINT: You can use the <code>attr</code> method on the circle object obtained.</p>
</div>
</div>
        </div>
      </div>
      <div class="footer">
        <a class="label swc-blue-bg" href="http://software-carpentry.org">Software Carpentry</a>
        <a class="label swc-blue-bg" href="https://github.com/swcarpentry/lesson-template">Source</a>
        <a class="label swc-blue-bg" href="mailto:<EMAIL>">Contact</a>
        <a class="label swc-blue-bg" href="LICENSE.html">License</a>
      </div>
    </div>
    <!-- Javascript placed at the end of the document so the pages load faster -->
    <script src="js/jquery.min.js"></script>
    <script src="css/bootstrap/bootstrap-js/bootstrap.js"></script>
  </body>
</html>


<|start_filename|>04-publishing-with-github.html<|end_filename|>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="generator" content="pandoc">
    <title>Software Carpentry: Publishing using Github</title>
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-theme.css" />
    <link rel="stylesheet" type="text/css" href="css/swc.css" />
    <link rel="alternate" type="application/rss+xml" title="Software Carpentry Blog" href="http://software-carpentry.org/feed.xml"/>
    <meta charset="UTF-8" />
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>
  <body class="lesson">
    <div class="container card">
      <div class="banner">
        <a href="http://software-carpentry.org" title="Software Carpentry">
          <img alt="Software Carpentry banner" src="img/software-carpentry-banner.png" />
        </a>
      </div>
      <div class="row">
        <div class="col-md-10 col-md-offset-1">
          <h1 class="title">Publishing using Github</h1>
          <h2 class="subtitle">Show us your art!</h2>
<div id="learning-objectives" class="objectives panel panel-warning">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-certificate"></span>Learning Objectives</h2>
</div>
<div class="panel-body">
<ul>
<li>Hosting your page on Github</li>
</ul>
</div>
</div>
<p>The next thing we want to do is show the world what we've made! There are different ways to go about this. One of the easiest ones is provided by <a href="https://github.com">Github</a>.</p>
<p>You should all have signed up for a Github account. If you haven't, now is the time!</p>
<p>As you might remember, Github uses git, which is a version control software that is used to track changes in text documents. This alone makes it perfect for hosting our code and enables us to travel back in time and undo errors that we might introduce.</p>
<p>Using git you can create so-called repositories in your folders. The folder and its subfolders are then tracked and git tells you immediately if and what has changed in the files that are contained within the repository. You can 'commit' to a change you made and synchronize your local repository with the one that is hosted on Github.</p>
<p>But what's even better is that Github gives us the possibility to turn every repository into a website.</p>
<p>First, let's create our new repository on Github:</p>
<ul>
<li>Sign in to Github (https://github.com)</li>
<li>Create a new repository and call it 'myartwork'</li>
</ul>
<p>Don't worry about the other options for now. Using git in the command line, the Github app for Windows and Mac OS X, or Sourcetree (https://www.sourcetreeapp.com/), clone this repository to get a local copy. Copy the file that contains your artwork into your local repository and call it 'index.html'. The reason for this is that 'index.html' is the default file that is loaded on the server.</p>
<p>Save the file, commit the change, and push the changes to the repository on Github.</p>
<p>Right now, our code is on the web, but we haven't told the Github to publish it yet. To do this, we create a branch called 'gh-pages'. To create this branch, navigate to your repository and click on where it says &quot;branch:master&quot;. An input field should appear. Type in 'gh-pages' and press enter. A new branch should have been created and you should be able to find your webpage at: http://username.github.io/myartwork (with your username in place of 'username'). From now on, remember to only commit/push to your gh-pages branch. Otherwise your changes will not show up.</p>
<div id="show-us-your-art-work" class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Show us your art work!</h2>
</div>
<div class="panel-body">
<p>Publish your art work and send us a link. It should be http://username.github.io/myartwork</p>
</div>
</div>
        </div>
      </div>
      <div class="footer">
        <a class="label swc-blue-bg" href="http://software-carpentry.org">Software Carpentry</a>
        <a class="label swc-blue-bg" href="https://github.com/swcarpentry/lesson-template">Source</a>
        <a class="label swc-blue-bg" href="mailto:<EMAIL>">Contact</a>
        <a class="label swc-blue-bg" href="LICENSE.html">License</a>
      </div>
    </div>
    <!-- Javascript placed at the end of the document so the pages load faster -->
    <script src="js/jquery.min.js"></script>
    <script src="css/bootstrap/bootstrap-js/bootstrap.js"></script>
  </body>
</html>


<|start_filename|>code/main07.js<|end_filename|>
// Load the data.
var dataUrl = "https://raw.githubusercontent.com/IsaKiko/D3-visualising-data/gh-pages/code/nations.json";
d3.json(dataUrl, function(nations) {

	// Create the SVG frame inside chart_area.
	var chart_area = d3.select("#chart_area");
	var frame = chart_area.append("svg");

	// Create canvas inside frame.
	var canvas = frame.append("g");

	// Set margins, width, and height.
	var margin = {top: 19.5, right: 19.5, bottom: 19.5, left: 39.5};
	var frame_width = 960;
	var frame_height = 350;
	var canvas_width = frame_width - margin.left - margin.right;
	var canvas_height = frame_height - margin.top - margin.bottom;

	
	// Set svg attributes width and height.
	frame.attr("width", frame_width);
	frame.attr("height", frame_height);


	// Shift the chart and make it slightly smaller than the svg canvas.
	canvas.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

})

<|start_filename|>09-d3exit.html<|end_filename|>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="generator" content="pandoc">
    <title>Software Carpentry: D3 - Add and remove</title>
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-theme.css" />
    <link rel="stylesheet" type="text/css" href="css/swc.css" />
    <link rel="alternate" type="application/rss+xml" title="Software Carpentry Blog" href="http://software-carpentry.org/feed.xml"/>
    <meta charset="UTF-8" />
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>
  <body class="lesson">
    <div class="container card">
      <div class="banner">
        <a href="http://software-carpentry.org" title="Software Carpentry">
          <img alt="Software Carpentry banner" src="img/software-carpentry-banner.png" />
        </a>
      </div>
      <div class="row">
        <div class="col-md-10 col-md-offset-1">
          <h1 class="title">D3 - Add and remove</h1>
          <h2 class="subtitle">Dynamically adding and removing data points</h2>
<div id="learning-objectives" class="objectives panel panel-warning">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-certificate"></span>Learning Objectives</h2>
</div>
<div class="panel-body">
<ul>
<li>Filtering data</li>
<li>Creating checkboxes</li>
<li>Adding and removing data points (d3.enter and d3.exit)</li>
</ul>
</div>
</div>
<p>Our plot is pretty busy. We might not want to display everything all the time. The goal for this lesson is to update the plot based on what kind of data we want to display.</p>
<p>First, we need to find a way to filter our data. We use the function <code>filter</code> to do this. Similar to previous functions (e.g. <code>map</code>), this function iterates over each of the elements in the array <code>nations</code>, temporarily calling it <code>nation</code>. It only includes elements in the new array <code>filtered_nations</code> if the function evaluates to 'true' for that element. Here this will be the case for nations whose population in 2009 was larger than 10,000,000.</p>
<pre class="js"><code>var filtered_nations = nations.filter(function(nation){
    return nation.population[nation.population.length-1] &gt; 10000000;
});</code></pre>
<div id="filtering-by-region" class="challenge panel panel-success">
<div class="panel-heading">
<h1><span class="glyphicon glyphicon-pencil"></span>Filtering by region</h1>
</div>
<div class="panel-body">
<p>You might have noticed that our data contains information about the region in which a country is.</p>
<ol style="list-style-type: decimal">
<li>Create a filter so that you only display data points from &quot;Sub-Saharan Africa&quot;.</li>
</ol>
</div>
</div>
<p>We have now hard-coded a criterion for the data we want to display. Naturally, we might want to change what data gets displayed interactively using elements on our page. Let's create some checkboxes that let us add and remove the regions that we want to include. To do this, we will have to switch back to our HTML file for a while.</p>
<p>Now, instead of displaying all the data all the time, we want to be able to choose which data we display. We will create a checkbox for each region and only display the data for the regions that are checked.</p>
<p>Checkboxes will need to be added to the HTML page. Since we want to add and remove data, we'll have to add a checkbox for each region like the following one. Checkbox elements are actually <code>input</code> elements with type <code>checkbox</code>. Initially, we want all checkboxes to be checked. We do this by setting the <code>checked</code> attribute of the element to 'checked'.</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;label&gt;&lt;input</span><span class="ot"> type=</span><span class="st">&quot;checkbox&quot;</span><span class="ot"> name=</span><span class="st">&quot;region&quot;</span><span class="ot"> class=</span><span class="st">&quot;region_cb&quot;</span><span class="ot"> value=</span><span class="st">&quot;Sub-Saharan Africa&quot;</span><span class="ot"> checked=</span><span class="st">&quot;checked&quot;</span><span class="kw">/&gt;</span> Sub-Saharan Africa<span class="kw">&lt;/label&gt;</span></code></pre>
<p>The next step is to add an event listener to the JavaScript file. Luckily, D3 provides us with some nice options. The <code>value</code> needs to be set to the region, because this is the value we want to filter our data by later.</p>
<pre class="js"><code>d3.selectAll(&quot;.region_cb&quot;).on(&quot;change&quot;, function () { &lt;--- stuff happens here ---&gt; });</code></pre>
<p>This line listens to all checkboxes that have the class <code>region_cb</code>. Every time a checkbox's status changes from checked to unchecked or unchecked to checked, the following function is executed.</p>
<p>Inside this function, we want to decide what happens based on which of the checkboxes got checked or unchecked. The first step to doing this is to read out the value of the checkbox. We set this value to the region string earlier. Reading it can be done using the <code>this</code> keyword. <code>this</code> inside a callback function refers to the element through which the function got called, in our case the checkbox.</p>
<pre class="js"><code>var type = this.value;</code></pre>
<p>Now that we have the region string saved in <code>type</code>, we want to add the data points for the new nations to include if the checkbox is now checked. Whether it is checked or not is stored in <code>this.checked</code>. To add the new nations to <code>filtered_nations</code>, we use the <code>concat</code> function, which, similar to the <code>concat</code> function we used with strings, joins the array given as an argument onto the end of the first array. Here we join <code>new_nations</code> onto the end of <code>filtered_nations</code>.</p>
<pre class="js"><code>if (this.checked) { // adding data points
  var new_nations = nations.filter(function(nation){ return nation.region == type;});
  filtered_nations = filtered_nations.concat(new_nations);
}</code></pre>
<p>This <code>if</code>-statement gets executed every time a checkbox is checked. To add the data points, we can use the <code>push</code>-function, which adds one object to an array at a time. First, we filter the nations we want to add, calling them <code>new_nations</code>. Next, we are looping through all new nations and add one at a time to the array <code>filtered_nations</code>.</p>
<p>We also have to initialise <code>filtered_nations</code> at the top of our script. Remember that there is a difference between the object and the name space, so in order to keep <code>nations</code> the way it is, we need to map the values instead of just using <code>=</code>.</p>
<pre class="js"><code>var filtered_nations = nations.map(function(nation) { return nation; });</code></pre>
<p>We are initially making <code>filtered_nations</code> be the same as <code>nations</code> because initially all of the checkboxes are checked and we are displaying the data from all of the nations. This also means that any checkbox that is changed from this point will actually be changing to the unchecked state and not entering the <code>if</code>-statement we just made. So we need to add some code to remove elements when the state of a checkbox changes to unchecked.</p>
<p>But before doing this, we need to learn how to remove elements using D3. This is done using the <code>exit()</code> function.</p>
<pre class="js"><code>dot.exit().remove();</code></pre>
<p>Whereas before <code>enter()</code> was used to append new elements to the plot, <code>exit()</code> is used to remove elements from the plot that are no longer in the dataset. Both functions compare the data that has been specified to what elements are in the plot (on the page). As for <code>enter()</code>, everything that follows <code>exit()</code> is performed for each of the elements that no longer have data points corresponding to them. Here (and in most cases) we want to remove these elements.</p>
<p>A good, brief explanation of this linking between data and elements on the page can be found <a href="http://bost.ocks.org/mike/join/">here</a>. This article discusses the three important functions used for this: <code>enter</code>, <code>exit</code>, and a third function <code>update</code> that we will get to shortly.</p>
<div id="removing-elements" class="challenge panel panel-success">
<div class="panel-heading">
<h1><span class="glyphicon glyphicon-pencil"></span>Removing elements</h1>
</div>
<div class="panel-body">
<ol style="list-style-type: decimal">
<li>Using an <code>else</code> case after the <code>if</code> statement, create a filter that removes elements from <code>filtered_data</code> that correspond to the checkbox that was just unchecked. (i.e. <code>else { filtered_nations = &lt;--- fill in this bit ---&gt;}</code>).</li>
</ol>
</div>
</div>
<p>As a last step, let's move <code>enter()</code> and <code>exit()</code> into a separate function. This will become useful when we want to update the data from different elements on the page.</p>
<pre class="js"><code>function update() {
  var dot = data_canvas.selectAll(&quot;.dot&quot;).data(filtered_nations, function(d){return d.name});

  dot.enter().append(&quot;circle&quot;).attr(&quot;class&quot;,&quot;dot&quot;)
                .style(&quot;fill&quot;, function(d) { return colorScale(d.region); });
                .attr(&quot;cx&quot;, function(d) { return xScale(d.income[d.income.length-1]); }) // this is how attr knows to work with the data
                .attr(&quot;cy&quot;, function(d) { return yScale(d.lifeExpectancy[d.lifeExpectancy.length-1]); })
                .attr(&quot;r&quot;, function(d) { return rScale(d.population[d.population.length-1]); });

  dot.exit().remove();
}</code></pre>
<p>This means that we now have to call the update function from our event listener after updating <code>filtered_nations</code> based on the checkbox change:</p>
<pre class="js"><code>d3.selectAll(&quot;.region_cb&quot;).on(&quot;change&quot;, function() {
  var type = this.value;
  if (this.checked) { // adding data points (not quite right yet)
    var new_nations = nations.filter(function(nation){ return nation.region == type;});
    filtered_nations = filtered_nations.concat(new_nations);
  } else { // remove data points from the data that match the filter
    filtered_nations = filtered_nations.filter(function(nation){ return nation.region != type;});
  }
  update();
});</code></pre>
<p>In order to create the plot when we first load the page, we will also have to call <code>update()</code> outside of our event listeners once.</p>
<div id="another-new-dimension" class="challenge panel panel-success">
<div class="panel-heading">
<h1><span class="glyphicon glyphicon-pencil"></span>Another new dimension</h1>
</div>
<div class="panel-body">
<ol style="list-style-type: decimal">
<li>Have the colour of circles represent the region. Use category20() to make a scale. You will then need to add <code>.style(&quot;fill&quot;, function(d) { &lt;-- fill in this bit ---&gt; });</code> to the enter() function.</li>
</ol>
</div>
</div>
<p>By the end of this lesson, your page should look something like this:</p>
<iframe src="code/index09.html" width="1000" height="600"></iframe>
        </div>
      </div>
      <div class="footer">
        <a class="label swc-blue-bg" href="http://software-carpentry.org">Software Carpentry</a>
        <a class="label swc-blue-bg" href="https://github.com/swcarpentry/lesson-template">Source</a>
        <a class="label swc-blue-bg" href="mailto:<EMAIL>">Contact</a>
        <a class="label swc-blue-bg" href="LICENSE.html">License</a>
      </div>
    </div>
    <!-- Javascript placed at the end of the document so the pages load faster -->
    <script src="js/jquery.min.js"></script>
    <script src="css/bootstrap/bootstrap-js/bootstrap.js"></script>
  </body>
</html>


<|start_filename|>xx-d3future.html<|end_filename|>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="generator" content="pandoc">
    <title>Software Carpentry: Beyond this content</title>
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-theme.css" />
    <link rel="stylesheet" type="text/css" href="css/swc.css" />
    <link rel="alternate" type="application/rss+xml" title="Software Carpentry Blog" href="http://software-carpentry.org/feed.xml"/>
    <meta charset="UTF-8" />
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>
  <body class="lesson">
    <div class="container card">
      <div class="banner">
        <a href="http://software-carpentry.org" title="Software Carpentry">
          <img alt="Software Carpentry banner" src="img/software-carpentry-banner.png" />
        </a>
      </div>
      <div class="row">
        <div class="col-md-10 col-md-offset-1">
          <h1 class="title">Beyond this content</h1>
          <h2 class="subtitle">...and now what??</h2>
<div id="learning-objectives" class="objectives panel panel-warning">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-certificate"></span>Learning Objectives</h2>
</div>
<div class="panel-body">
<ul>
<li>How do I make the plot I want?</li>
<li>What are alternatives to using D3 to create pretty plots?</li>
</ul>
</div>
</div>
<p>Choosing the right plot for your data is the first step to making it as accessible as possible. Even though bubble plots are objectively beautiful, they might not be the best choice for your specific data.</p>
<p>Other people have thought about this, too, and came up with this chart, that might come in handy: <img src="img/choose_right_chart.png" alt="Choose your chart" width="900" /> <a href="https://www.flickr.com/photos/amit-agarwal/3196386402/">Source</a></p>
<p>You can get more inspiration on <a href="http://d3js.org">d3js.org</a>. Here, you will find plenty of beautiful examples of plots that people have already made as well as a whole gallery of almost everything you can imagine with the according code right underneath it.</p>
<p><img src="img/d3-screenshot.png" alt="D3 webpage" width="900" /></p>
<p>Most of the examples happily link you to their code so you can go through it and modify it to suit your data. Some examples don't volunteer their code like this. But through the beauty of the internet, all that code is online, too, and we can have a look at it using the browser's developer tools (right click, 'inspect element').</p>
<p>This workshop tries to give you the tools you need to download someone's code and modify it for your needs. There are of course other ways you can create plots. Some handy packages that are online are:</p>
<ul>
<li><a href="http://www.highcharts.com/">highcharts</a></li>
<li><a href="https://plot.ly/feed/">plot.ly</a></li>
<li><a href="http://nvd3.org/">nvd3</a></li>
<li><a href="http://www.cytoscape.org/">cytoscape</a></li>
<li><a href="http://dimplejs.org/">dimplejs</a></li>
<li><a href="http://metricsgraphicsjs.org/">metricsgraphics</a></li>
</ul>
<p>Not all of them are free and not all of them are completely customisable, but they often offer a quicker and easier ways to create plots that you can then put online.</p>
        </div>
      </div>
      <div class="footer">
        <a class="label swc-blue-bg" href="http://software-carpentry.org">Software Carpentry</a>
        <a class="label swc-blue-bg" href="https://github.com/swcarpentry/lesson-template">Source</a>
        <a class="label swc-blue-bg" href="mailto:<EMAIL>">Contact</a>
        <a class="label swc-blue-bg" href="LICENSE.html">License</a>
      </div>
    </div>
    <!-- Javascript placed at the end of the document so the pages load faster -->
    <script src="js/jquery.min.js"></script>
    <script src="css/bootstrap/bootstrap-js/bootstrap.js"></script>
  </body>
</html>


<|start_filename|>08-d3enter.html<|end_filename|>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="generator" content="pandoc">
    <title>Software Carpentry: D3 - Into the data</title>
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-theme.css" />
    <link rel="stylesheet" type="text/css" href="css/swc.css" />
    <link rel="alternate" type="application/rss+xml" title="Software Carpentry Blog" href="http://software-carpentry.org/feed.xml"/>
    <meta charset="UTF-8" />
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>
  <body class="lesson">
    <div class="container card">
      <div class="banner">
        <a href="http://software-carpentry.org" title="Software Carpentry">
          <img alt="Software Carpentry banner" src="img/software-carpentry-banner.png" />
        </a>
      </div>
      <div class="row">
        <div class="col-md-10 col-md-offset-1">
          <h1 class="title">D3 - Into the data</h1>
          <h2 class="subtitle">Actually plotting things</h2>
<div id="learning-objectives" class="objectives panel panel-warning">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-certificate"></span>Learning Objectives</h2>
</div>
<div class="panel-body">
<ul>
<li>Making axes</li>
<li>Actually plotting data (d3.enter)</li>
</ul>
</div>
</div>
<p>We design our axes based on our data. This means we have to know the minimum and maximum values of our data and have to decide whether we want linear or logarithmic axes.</p>
<pre class="js"><code>// Create a logarithmic scale for the income
var xScale = d3.scale.log(); // income
xScale.domain([250, 1e5]); // set minimum and maximum value
xScale.range([0, canvas_width]); // set minimum and maximum range on the page</code></pre>
<p>D3's scale object provides a number of functions to create the scaling we want for our data. For example, we can choose between a logarithmic scale (<code>log</code>), a linear scale (<code>linear</code>), a square root scale (<code>sqrt</code>), or a categorical scale (e.g. <code>category20</code> could represent 20 different colours).</p>
<p>The domain consists of the data values that will get mapped to the minimum and maximum positions on the page specified by the range. Often, the domain would be set to the minimum and maximum values of the data and the range to the edges of the plotting area.</p>
<p>Instead of spreading this code over three lines, we often find another notation online that achieves the same thing:</p>
<pre class="js"><code>var xScale = d3.scale.log().domain([300, 1e5]).range([0, canvas_width]);  </code></pre>
<p>These two notations are interchangeable and it is entirely up to you to use the one that seems more intuitive to you. In the same way that we could switch setting up the domain and range in the more verbose notation, we can swap these two in the shorter notation without it making any difference.</p>
<p>The next step is to create the actual axis and linking it to the scale we just created:</p>
<pre class="js"><code>// Creating the x &amp; y axes.
var xAxis = d3.svg.axis().orient(&quot;bottom&quot;).scale(xScale);</code></pre>
<p>We also want to orient it horizontally, at the bottom of our canvas.</p>
<p>So far, the xAxis exists, but it's not actually showing up anywhere on the page. To push the axis to our canvas, we create a new group element (using <code>.append</code>).</p>
<pre class="js"><code>// Add the x-axis.
canvas.append(&quot;g&quot;)
    .attr(&quot;class&quot;, &quot;x axis&quot;)
  .attr(&quot;transform&quot;, &quot;translate(0,&quot; + canvas_height + &quot;)&quot;)
  .call(xAxis);</code></pre>
<p><code>.call</code> calls the axis we just created and pushed it to the element. We add a transform attribute to move the axis to the bottom of the plotting area (instead of having it across the top). There are a number of transform options, but here we are just using <code>translate</code> and pass in the amount to shift the axis in the x and y directions, respectively. Here we shift it only in the y direction (i.e. down) by an amount given by height of the canvas.<br />We also give it a class, just in case we might want to select the axis later in our code.</p>
<div id="we-might-need-a-y-axis-too" class="challenge panel panel-success">
<div class="panel-heading">
<h1><span class="glyphicon glyphicon-pencil"></span>We might need a y-axis, too</h1>
</div>
<div class="panel-body">
<ol style="list-style-type: decimal">
<li>Create a linear scale for the y-axis, with 10 being the minimum and 85 being the maximum value. Then, add the axis to the canvas.</li>
</ol>
</div>
</div>
<p>We're slowly getting there. Having our two axes, we can now finally add our data.</p>
<p>And now we're ready to add one circle per data point! We don't want to see all the data at once for now. Let's instead just look at the most recent data point (data for 2009).</p>
<p><img src="img/data_structure.png" alt="data structure" width="500" /></p>
<pre class="js"><code>var data_canvas = canvas.append(&quot;g&quot;)
  .attr(&quot;class&quot;, &quot;data_canvas&quot;);

var dot = data_canvas.selectAll(&quot;.dot&quot;)
  .data(nations, function(d){return d.name});

dot.enter().append(&quot;circle&quot;).attr(&quot;class&quot;,&quot;dot&quot;)
  .attr(&quot;cx&quot;, function(d) { return xScale(d.income[d.income.length-1]); })
  .attr(&quot;cy&quot;, function(d) { return yScale(d.lifeExpectancy[d.lifeExpectancy.length-1]); })
  .attr(&quot;r&quot;, 5);</code></pre>
<p>We're starting this bit by adding a <code>g</code> element to our canvas. This group is going to be our data canvas, so that's the class name we give it. We then select everything of the class <code>dot</code>. This is an empty set at the moment, since we haven't created any dots, yet. We are then telling our page where to find the data, using <code>.data(nations)</code>.</p>
<p>We are also inserting what is called a key function <code>.data(nations, function(d){return d.name});</code>. This function will help D3 keep track of the data when we start changing it (and the order of the objects). It's important to keep the identifier unique, which is why we return only the name of the current element.</p>
<p>Now comes the interesting part: The function <code>enter()</code> takes each element in the dataset and does everything that follows afterwards for each of these elements we're adding in. These new dots need to be added with the class 'dot', so that next time we call <code>data_canvas.selectAll(&quot;.dot&quot;)</code> we get the dots that have already been added to our plot.</p>
<p>What we want to do is to create one circle for each data point. That's what the last four lines of code do. They are creating the circle, and then setting the attributes <code>cx</code>, <code>cy</code>, and <code>r</code>. The attributes <code>cx</code> and <code>cy</code> define the position of the centre of the circle and are based on the income (we are looking at the most recent data point: <code>[nation.income.length-1]</code>.) and life expectancy of the data point (that is temporarily called <code>d</code>). The radius is set to an arbitrary number... for now.</p>
<div id="a-new-dimension" class="challenge panel panel-success">
<div class="panel-heading">
<h1><span class="glyphicon glyphicon-pencil"></span>A new dimension</h1>
</div>
<div class="panel-body">
<p>Change the code so that the radius of the circles represents the population. First, create a 'sqrt' scale with a minimum of 0 and a maximum of 5e8. The range should be between 0 and 40. </p>
</div>
</div>
<iframe src="code/index08.html" width="1000" height="600"></iframe>
        </div>
      </div>
      <div class="footer">
        <a class="label swc-blue-bg" href="http://software-carpentry.org">Software Carpentry</a>
        <a class="label swc-blue-bg" href="https://github.com/swcarpentry/lesson-template">Source</a>
        <a class="label swc-blue-bg" href="mailto:<EMAIL>">Contact</a>
        <a class="label swc-blue-bg" href="LICENSE.html">License</a>
      </div>
    </div>
    <!-- Javascript placed at the end of the document so the pages load faster -->
    <script src="js/jquery.min.js"></script>
    <script src="css/bootstrap/bootstrap-js/bootstrap.js"></script>
  </body>
</html>


<|start_filename|>10-d3update.html<|end_filename|>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="generator" content="pandoc">
    <title>Software Carpentry: D3 - Transitions</title>
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-theme.css" />
    <link rel="stylesheet" type="text/css" href="css/swc.css" />
    <link rel="alternate" type="application/rss+xml" title="Software Carpentry Blog" href="http://software-carpentry.org/feed.xml"/>
    <meta charset="UTF-8" />
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>
  <body class="lesson">
    <div class="container card">
      <div class="banner">
        <a href="http://software-carpentry.org" title="Software Carpentry">
          <img alt="Software Carpentry banner" src="img/software-carpentry-banner.png" />
        </a>
      </div>
      <div class="row">
        <div class="col-md-10 col-md-offset-1">
          <h1 class="title">D3 - Transitions</h1>
          <h2 class="subtitle">Move it!</h2>
<div id="learning-objectives" class="objectives panel panel-warning">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-certificate"></span>Learning Objectives</h2>
</div>
<div class="panel-body">
<ul>
<li>Using a slider</li>
<li>Updating data points using d3.transition</li>
<li>Putting it all together by adding regional averages in a master challenge!</li>
</ul>
</div>
</div>
<p>At the moment, the year that we are looking at in the data is hardcoded. Naturally, we want the user to be able to see how the data changes over time.</p>
<p>Let's do this a slider. The first thing we need is add this slider to the user interface (our website). A slider element is actually an <code>input</code> element with the the type <code>range</code>. We give it a ID in order to be able to select is from our JavaScript script, a class to style it (if we choose to), and a minimum, maximum, and step size that depend on our data. <code>value</code> is what we read out in order to know the position of the slider. Let's initialise it somewhere in the middle (1979).</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;input</span><span class="ot"> type=</span><span class="st">&quot;range&quot;</span><span class="ot"> name=</span><span class="st">&quot;range&quot;</span><span class="ot"> class=</span><span class="st">&quot;slider&quot;</span><span class="ot"> id=</span><span class="st">&quot;year_slider&quot;</span><span class="ot"> value=</span><span class="st">&quot;1979&quot;</span><span class="ot"> min=</span><span class="st">&quot;1950&quot;</span><span class="ot"> max=</span><span class="st">&quot;2008&quot;</span><span class="ot"> step=</span><span class="st">&quot;1&quot;</span> <span class="kw">&gt;&lt;br&gt;</span></code></pre>
<p>In our script, we now want the year to be a variable, so we need to initialise it. Because the value is a string, we need to parse it to an integer using <code>parseInt()</code>. To get the index (rather than the actual year), we can simply subtract the first year 1950.</p>
<pre class="js"><code>var year_idx = parseInt(document.getElementById(&quot;year_slider&quot;).value)-1950;</code></pre>
<p>Updating the year becomes quite simple. All we need to do is add another event listener that changes the year the moment we touch the slider. The event we want to listen for is called <code>input</code>. We then execute the <code>update()</code> function we wrote earlier.</p>
<pre class="js"><code>d3.select(&quot;#year_slider&quot;).on(&quot;input&quot;, function () {
    year_idx = parseInt(this.value) - 1950;
    update();
});</code></pre>
<p>So far, the update function only knows how to handle new data (<code>.enter</code>) and removed data (<code>.exit</code>), but not what to do when we update data. In addition to <code>d3.enter()</code> and <code>d3.exit()</code>, D3 also offers <code>d3.transition</code> to handle updating data. First, we need to define how to transition between data points. We might want to interpolate between to values linearly over the duration of 200 ms, like this:</p>
<pre class="js"><code>dot.transition().ease(&quot;linear&quot;).duration(200);</code></pre>
<p>Now we know how it's gonna happen, but we need to tell the transition what the actual change is. We can simply move the part of our code that updates the circle attributes from our <code>enter</code> function to our <code>transition</code> function. Now, instead of using a hardcoded index for the year, we use the index <code>year_idx</code> that we updated in our event listener earlier.</p>
<pre class="js"><code>dot.enter().append(&quot;circle&quot;).attr(&quot;class&quot;,&quot;dot&quot;)
        .style(&quot;fill&quot;, function(d) { return colorScale(d.region); });
dot.exit().remove();
dot.transition().ease(&quot;linear&quot;).duration(200)
                .attr(&quot;cx&quot;, function(d) { return xScale(d.income[year_idx]); }) // this is how attr knows to work with the data
                .attr(&quot;cy&quot;, function(d) { return yScale(d.lifeExpectancy[year_idx]); })
                .attr(&quot;r&quot;, function(d) { return rScale(d.population[year_idx]); });</code></pre>
<div id="other-transition-functions-you-might-want" class="callout panel panel-info">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pushpin"></span>Other transition functions you might want</h2>
</div>
<div class="panel-body">
<ul>
<li>sin - applies the trigonometric function sin.</li>
<li>exp - raises 2 to a power based on t.</li>
<li>bounce - simulates a bouncy collision.</li>
<li>elastic(a, p) - simulates an elastic band; may extend slightly beyond 0 and 1.</li>
<li><a href="https://github.com/mbostock/d3/wiki/Transitions#d3_ease">more here</a></li>
</ul>
</div>
</div>
<div id="play-time" class="challenge panel panel-success">
<div class="panel-heading">
<h1><span class="glyphicon glyphicon-pencil"></span>Play time</h1>
</div>
<div class="panel-body">
<p>D3 is incredible versatile. Try out different transitions and if you have time, maybe try drawing rectangles instead of circles.</p>
</div>
</div>
<p>Next, we might want to create a tooltip. Let's go have a look at what's already out there. The creator of D3 has put up some code for pretty much everything you can imagine. The example for a simple tooltip can be found <a href="http://bl.ocks.org/biovisualize/1016860">here</a>. We need to first create the variable tooltip:</p>
<pre class="js"><code>var tooltip = d3.select(&quot;body&quot;)
    .append(&quot;div&quot;)
    .style(&quot;position&quot;, &quot;absolute&quot;)
    .style(&quot;visibility&quot;, &quot;hidden&quot;);</code></pre>
<p>and then create event listeners for moving the mouse into a circle and out of one. Different from the example on the web page, we want to display the specific country we are looking at. When we move the mouse, we want the tool tip to move with it. And the moment we leave a circle, we want the tool tip to hide again.</p>
<pre class="js"><code>dot.enter().append(&quot;circle&quot;).attr(&quot;class&quot;,&quot;dot&quot;)
            .style(&quot;fill&quot;, function(d) { return colorScale(d.region); })
            .on(&quot;mouseover&quot;, function(d){return tooltip.style(&quot;visibility&quot;, &quot;visible&quot;).text(d.name);})
            .on(&quot;mousemove&quot;, function(){return tooltip.style(&quot;top&quot;, (d3.event.pageY-10)+&quot;px&quot;).style(&quot;left&quot;,(d3.event.pageX+10)+&quot;px&quot;);})
            .on(&quot;mouseout&quot;, function(){return tooltip.style(&quot;visibility&quot;, &quot;hidden&quot;);});</code></pre>
<div id="we-have-used-some-special-objects-given-to-us-by-the-browser" class="callout panel panel-info">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pushpin"></span>We have used some special objects given to us by the browser</h2>
</div>
<div class="panel-body">
<ul>
<li>document.x - selecting things within the page (getElementById)</li>
<li>console.x - interact with the browser's console (log)</li>
<li>event.x - only interesting in the scope of an event like &quot;mouseover&quot;, &quot;mousemove&quot;, &quot;keydown&quot;. Returns information about the event (pageX - where on the page did this event occur?).</li>
</ul>
</div>
</div>
<p>Like any programming language, JavaScript can also be used to evaluate summary statistics of our data. As an example, let's compute the mean life expectancy and income for the different regions.</p>
<p>First, we need to loop through all the data and group them by the region they are in:</p>
<pre class="js"><code>// Calculate the averages for each region.
var region_names = [&quot;Sub-Saharan Africa&quot;, &quot;South Asia&quot;, &quot;Middle East &amp; North Africa&quot;, &quot;America&quot;, &quot;East Asia &amp; Pacific&quot;, &quot;Europe &amp; Central Asia&quot;];

var region_data = [];
for (var i in region_names) {
    var filtered_nations_by_regions = nations.filter(function(nation){
        return (nation.region == region_names[i]);
    });
    region_data[i] = calc_mean(filtered_nations_by_regions);
}

var filtered_reg_nations = region_data.map(function(region) { return region;});</code></pre>
<p>Next, we write a function that returns an array of objects region_data. We want it to contain the mean income and life for each year across all nations, weighted by population.</p>
<pre class="js"><code>function calc_mean(region_data) {
    var mean_income = [];
    var mean_lifeExpectancy = [];

    for (var year_idx2 in region_data[0].years) {
        var sum_income = 0;
        var sum_lifeExpectancy = 0;
        var sum_population = 0;

        for (var k in region_data) {
            var kpop = region_data[k].population[year_idx2];
            var kincome = region_data[k].income[year_idx2];
            var klife = region_data[k].lifeExpectancy[year_idx2];
            sum_income += kpop*kincome;
            sum_lifeExpectancy += kpop*klife;
            sum_population += kpop;
        }

        mean_income[year_idx2] = sum_income/sum_population;
        mean_lifeExpectancy[year_idx2] = sum_lifeExpectancy/sum_population;
    }
    averageData = {
        region: region_data[0].region,
        years: region_data[0].years,
        mean_income: mean_income,
        mean_lifeExpectancy: mean_lifeExpectancy
    };

    return averageData;
}</code></pre>
<div id="the-master-challenge" class="challenge panel panel-success">
<div class="panel-heading">
<h1><span class="glyphicon glyphicon-pencil"></span>The master challenge</h1>
</div>
<div class="panel-body">
<p>It's time to put together everything you've learned. Write code that displays (and updates) the mean values that we just computed as little crosses in the graph for the different regions.</p>
</div>
</div>
<div id="style" class="challenge panel panel-success">
<div class="panel-heading">
<h1><span class="glyphicon glyphicon-pencil"></span>...style!</h1>
</div>
<div class="panel-body">
<p>Add axis labels and make the fonts pretty.</p>
</div>
</div>
<div id="using-different-data-formats" class="challenge panel panel-success">
<div class="panel-heading">
<h1><span class="glyphicon glyphicon-pencil"></span>Using different data formats</h1>
</div>
<div class="panel-body">
<p>What if you don't have your data in JSON format? Change your code to load in nations.csv instead of nations.json and have it produce the same plot.</p>
</div>
</div>
<p>By the end of this lesson, your page should look something like this:</p>
<iframe src="code/index10.html" width="1000" height="600"></iframe>
        </div>
      </div>
      <div class="footer">
        <a class="label swc-blue-bg" href="http://software-carpentry.org">Software Carpentry</a>
        <a class="label swc-blue-bg" href="https://github.com/swcarpentry/lesson-template">Source</a>
        <a class="label swc-blue-bg" href="mailto:<EMAIL>">Contact</a>
        <a class="label swc-blue-bg" href="LICENSE.html">License</a>
      </div>
    </div>
    <!-- Javascript placed at the end of the document so the pages load faster -->
    <script src="js/jquery.min.js"></script>
    <script src="css/bootstrap/bootstrap-js/bootstrap.js"></script>
  </body>
</html>


<|start_filename|>02-css.html<|end_filename|>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="generator" content="pandoc">
    <title>Software Carpentry: CSS</title>
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-theme.css" />
    <link rel="stylesheet" type="text/css" href="css/swc.css" />
    <link rel="alternate" type="application/rss+xml" title="Software Carpentry Blog" href="http://software-carpentry.org/feed.xml"/>
    <meta charset="UTF-8" />
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>
  <body class="lesson">
    <div class="container card">
      <div class="banner">
        <a href="http://software-carpentry.org" title="Software Carpentry">
          <img alt="Software Carpentry banner" src="img/software-carpentry-banner.png" />
        </a>
      </div>
      <div class="row">
        <div class="col-md-10 col-md-offset-1">
          <h1 class="title">CSS</h1>
          <h2 class="subtitle">Doing it in style</h2>
<div id="learning-objectives" class="objectives panel panel-warning">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-certificate"></span>Learning Objectives</h2>
</div>
<div class="panel-body">
<ul>
<li>Change the appearance of different HTML elements</li>
<li>Create new classes in a CSS file</li>
<li>Apply these classes to different HTML elements</li>
</ul>
</div>
</div>
<p>The heading has a certain look. This look (or style) includes the color, position, font size, as well as many other attributes.</p>
<p>We can change the appearance of our text in different ways. A quick way is to simply mention what we want our element to look like when we create it by setting the &quot;style&quot; attribute. If we want to change the color, for example, we write:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;h1</span><span class="ot"> style=</span><span class="st">&quot;color:blue&quot;</span><span class="kw">&gt;</span>This is a blue heading<span class="kw">&lt;/h1&gt;</span></code></pre>
<p>Changing the font size:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;h1</span><span class="ot"> style=</span><span class="st">&quot;font-size: 80px&quot;</span><span class="kw">&gt;</span>This is a big heading<span class="kw">&lt;/h1&gt;</span></code></pre>
<p>If we want to change two things at the same time, we just mention all of them at once:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;h1</span><span class="ot"> style=</span><span class="st">&quot;font-size: 80px; color: blue&quot;</span><span class="kw">&gt;</span>This is a big, blue heading<span class="kw">&lt;/h1&gt;</span></code></pre>
<p>This is a quick and simple way to change the appearance of elements on the spot. However, if we want to create different elements of the same type, we have to do a lot of typing, and our file will quickly become confusing and hard to maintain.</p>
<p>If we want to change the look of many elements at the same time, we can instead create a style file (extension .css).</p>
<ul>
<li>create a CSS file: styles.css</li>
</ul>
<p>In this file, we can define classes, that we can then apply to one or more of our elements in the HTML file. Let's create a class called 'title' that we want to apply to different elements on our page.</p>
<pre class="sourceCode css"><code class="sourceCode css"><span class="fl">.title</span>
<span class="kw">{</span>
    <span class="kw">color:</span> <span class="dt">red</span><span class="kw">;</span>
    <span class="kw">font-size:</span> <span class="dt">50px</span><span class="kw">;</span>
    <span class="kw">text-align:</span> <span class="dt">center</span><span class="kw">;</span>
<span class="kw">}</span></code></pre>
<p>All that's left to do, is to tell the HTML file where to find our new CSS file. This is done by linking to it in the head:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="dt">&lt;!DOCTYPE </span>html<span class="dt">&gt;</span>
<span class="kw">&lt;html&gt;</span>
    <span class="kw">&lt;head&gt;</span>
        <span class="kw">&lt;link</span><span class="ot"> rel=</span><span class="st">&quot;stylesheet&quot;</span><span class="ot"> type=</span><span class="st">&quot;text/css&quot;</span><span class="ot"> href=</span><span class="st">&quot;styles.css&quot;</span><span class="kw">&gt;</span>
    <span class="kw">&lt;/head&gt;</span> </code></pre>
<p>In the body, we can use the class that we just created:</p>
<pre class="sourceCode html"><code class="sourceCode html">    <span class="kw">&lt;body&gt;</span>
        <span class="kw">&lt;div</span><span class="ot"> class=</span><span class="st">&quot;title&quot;</span><span class="kw">&gt;</span> First title <span class="kw">&lt;/div&gt;</span>
        <span class="kw">&lt;div&gt;</span> some text <span class="kw">&lt;/div&gt;</span>
        <span class="kw">&lt;div</span><span class="ot"> class=</span><span class="st">&quot;title&quot;</span><span class="kw">&gt;</span> And another title <span class="kw">&lt;/div&gt;</span>
    <span class="kw">&lt;/body&gt;</span>
<span class="kw">&lt;/html&gt;</span> </code></pre>
<div id="create-and-use-your-own-class" class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Create and use your own class</h2>
</div>
<div class="panel-body">
<p>Create a class called 'description' and a 'div' element with text that has this class. Make the text dark gray with a custom font size. Add a black border just on the left side of the 'div' and add padding around the text. Try adding in enough text so that it wraps over multiple lines, and then set the width of the 'div' to different values. Try setting the background color of the 'div' element. If you like, play with the 'title' class as well, until you like how it looks.</p>
</div>
</div>
<p>We can check out how our elements are styled in the developer tools. To get to them, right-click on any element on the page and select 'Inspect element'. The developer tools should open and you should be in the 'Elements' tab. Here, you can navigate through the html file and inspect css properties at the same time.</p>
        </div>
      </div>
      <div class="footer">
        <a class="label swc-blue-bg" href="http://software-carpentry.org">Software Carpentry</a>
        <a class="label swc-blue-bg" href="https://github.com/swcarpentry/lesson-template">Source</a>
        <a class="label swc-blue-bg" href="mailto:<EMAIL>">Contact</a>
        <a class="label swc-blue-bg" href="LICENSE.html">License</a>
      </div>
    </div>
    <!-- Javascript placed at the end of the document so the pages load faster -->
    <script src="js/jquery.min.js"></script>
    <script src="css/bootstrap/bootstrap-js/bootstrap.js"></script>
  </body>
</html>


<|start_filename|>05-javascript.html<|end_filename|>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="generator" content="pandoc">
    <title>Software Carpentry: JavaScript</title>
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-theme.css" />
    <link rel="stylesheet" type="text/css" href="css/swc.css" />
    <link rel="alternate" type="application/rss+xml" title="Software Carpentry Blog" href="http://software-carpentry.org/feed.xml"/>
    <meta charset="UTF-8" />
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>
  <body class="lesson">
    <div class="container card">
      <div class="banner">
        <a href="http://software-carpentry.org" title="Software Carpentry">
          <img alt="Software Carpentry banner" src="img/software-carpentry-banner.png" />
        </a>
      </div>
      <div class="row">
        <div class="col-md-10 col-md-offset-1">
          <h1 class="title">JavaScript</h1>
          <h2 class="subtitle">Feeding a cat</h2>
<div id="learning-objectives" class="objectives panel panel-warning">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-certificate"></span>Learning Objectives</h2>
</div>
<div class="panel-body">
<ul>
<li>Linking to a JavaScript file</li>
<li>Passing HTML element tags to JavaScript</li>
<li>Manipulating HTML elements using JavaScript</li>
</ul>
</div>
</div>
<p>We've learned how to integrate text and graphical objects into our page and we also know how to publish it. So far, we might as well just create a plot elsewhere and publish it as an image. But wouldn't it be much better, if the user could interact with the data? To do that, we need to learn a little scripting, and, again, HTML provides a scripting environment. Everything between &lt;script&gt; and &lt;/script&gt; within the body will be interpreted as JavaScript code. Since the code we write in the HTML file is executed sequentially, we need to make sure that whenever we refer to an element on the page, this element already exists. An easy way to ensure this is to include scripts just before the end of the body element. Just like we did with styles, we can outsource our code into a separate file with the extension <code>.js</code>.</p>
<p>So, let's go back to using the cat image for now. We want the cat to acknowledge that we click on it. First we need to create our <code>interaction.js</code> file and link to it in the HTML body.</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;script</span><span class="ot"> src=</span><span class="st">&quot;interaction.js&quot;</span><span class="kw">&gt;&lt;/script&gt;</span></code></pre>
<p>We need to introduce the script to the HTML element, using these basic steps:</p>
<ul>
<li>Set up a link between HTML and the script by giving the HTML element we want to interact with a unique ID.</li>
<li>Retrieving the element and assigning it to a variable in the script that we can work with.</li>
<li>Detect the action we are interested in, i.e. button click using an event listener.</li>
<li>Do things.</li>
</ul>
<p>The ID is an attribute we can set for the image:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;div</span><span class="ot"> class=</span><span class="st">&#39;image&#39;</span><span class="kw">&gt;</span>
    <span class="kw">&lt;img</span><span class="ot"> id=</span><span class="st">&quot;cat&quot;</span><span class="ot"> src=</span><span class="st">&quot;img/cat.jpg&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;/div&gt;</span></code></pre>
<p>Using <code>getElementById</code>, we can grab the element from <code>document</code> (a magical object representing the entire page) and work with it in the JavaScript file.</p>
<pre class="js"><code>var cat_image = document.getElementById(&#39;cat&#39;);</code></pre>
<p>Now we want to detect if someone clicks on the cat image. Event listeners help us by constantly checking if someone performs a certain action.</p>
<pre class="js"><code>var cat_image = document.getElementById(&#39;cat&#39;);
cat_image.addEventListener(&quot;click&quot;, meow);</code></pre>
<p>Our event listener takes two arguments: the type of event and what we want it to do. We want to execute a function called <code>meow()</code>, which will open a pop-up window. We can use the JavaScript function alert().</p>
<pre class="js"><code>function meow() {
    alert(&quot;Meow!&quot;);
};</code></pre>
<p>If we want to execute a sequence of functions, we can also create something that's called <code>inline</code> function, that is only defined in the scope of this specific callback. Within this function, we can call <code>meow()</code>, but also othe functions, like <code>purr()</code> (which doesn't exist, yet).</p>
<pre class="js"><code>var cat_image = document.getElementById(&#39;cat&#39;);
cat_image.addEventListener(&quot;click&quot;, function() {
    meow();
    purr();
});</code></pre>
<p>Obviously, we can also drop the <code>meow()</code> function, if we don't want to use it ever again:</p>
<pre class="js"><code>var cat_image = document.getElementById(&#39;cat&#39;);
cat_image.addEventListener(&quot;click&quot;, function() {
    alert(&quot;Meow!&quot;);
    purr();
});</code></pre>
<div id="debugging-in-a-browser" class="callout panel panel-info">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pushpin"></span>Debugging in a browser</h2>
</div>
<div class="panel-body">
<p>If we right click anywhere on our page and select &quot;Inspect Element&quot;, the browser takes us to the developer tools. Here, we have different tabs. The three most important ones are:</p>
<ul>
<li>Console - The console alerts us to things going wrong in out code by showing us an error and telling us in what line the error ocurred. We can also display the values of variables by including <code>colsole.log(x)</code> in our code.</li>
<li>Elements - If we want to know if our HTML elements are all in the right spot, this is where we need to look. Hovering over any part of the page will highlight the according element and we can look at how they are styled and temporarily change attributes.</li>
<li>Sources - Here, we can look at the files that are used by our page. And even better, if we navigate to the JavaScript file, we can add breakpoints that stay in place when we reload the page. This allows us to investigate values of variables on the spot.</li>
</ul>
</div>
</div>
<div id="feed-your-pet-cat" class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Feed your pet cat</h2>
</div>
<div class="panel-body">
<p>Create a button using the &lt;button&gt; element to feed the cat using the steps outlined earlier. Use the alert() function to have the cat thank you.</p>
</div>
</div>
<p>The next step to having a fully interactive page is to change HTML elements using JavaScript. We've created a button in the HTML file and are calling a function when it is clicked. The goal now is to make the cat put on a little bit of weight when we feed it. We have to link to both the cat element and the food button so that both files know what we're talking about.</p>
<p>We're setting the width by stringing a few words together: 'cat_image.style.width'. We can think of 'cat_image' as having an attribute called 'style', which in turn has an attribute called 'width'. Let's add a couple of grams. We have to retrieve the current object width. Our 'cat_image' object also has a attribute called 'offsetWidth'. This will give us the current width as a number (as opposed to the string '200px'). Google is your friend here. Use it to find out these handy functions. Lastly we have to append the new value with 'px'.</p>
<pre class="js"><code>var cat_image = document.getElementById(&#39;cat&#39;);
var feed_button = document.getElementById(&#39;feed_button&#39;);

feed_button.addEventListener(&quot;click&quot;, feed);
function feed() {
    cat_image.style.width = (cat_image.offsetWidth + 30.0) + &#39;px&#39;;
};</code></pre>
<p>We could also pass an argument into the <code>feed</code> function by writing it in the brackets. We might, for example, want the user to be able to decide the meal size the cat eats.</p>
<p>We can also return a value and assign it to a variable (just like we do with any function we used so far, e.g. var element = document.getElementById(&quot;someID&quot;);):</p>
<pre class="js"><code>var new_width = feed(10);

function feed(mealsize) {
        cat_image.style.width = (cat_image.offsetWidth + parseInt(mealsize)) + &#39;px&#39;;
        return cat_image.style.width;
};</code></pre>
<p>In JavaScript there are two main data types: strings (text, everything in quotes) and numbers. It's important to remember that you can't do maths with strings or append numbers together.</p>
<p>For example: <code>5+5 = 10</code> but <code>'5'+'5' = '55'</code></p>
<p>If one of the arguments is a string, the other one gets converted, too: <code>5 + '5' = '55'</code></p>
<p>We've also just used that, when we concatenated <code>(cat_image.offsetWidth + 30.0) + 'px'</code>.</p>
<div id="other-event-listeners-that-might-come-in-handy" class="callout panel panel-info">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pushpin"></span>Other event listeners, that might come in handy</h2>
</div>
<div class="panel-body">
<ul>
<li>dblclick - Double click</li>
<li>contextmenu - Right click</li>
<li>mouseover - Mouse moved over an element</li>
<li>keypress - Key pressed on keyboard</li>
</ul>
</div>
</div>
<div id="let-the-cat-work-out" class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Let the cat work out</h2>
</div>
<div class="panel-body">
<p>Create a second button 'run around the block', that makes the cat slimmer again.</p>
</div>
</div>
<p>By the end of this lesson, your page should look something like this:</p>
<iframe src="code/meow.html" width="1000" height="250"></iframe>
        </div>
      </div>
      <div class="footer">
        <a class="label swc-blue-bg" href="http://software-carpentry.org">Software Carpentry</a>
        <a class="label swc-blue-bg" href="https://github.com/swcarpentry/lesson-template">Source</a>
        <a class="label swc-blue-bg" href="mailto:<EMAIL>">Contact</a>
        <a class="label swc-blue-bg" href="LICENSE.html">License</a>
      </div>
    </div>
    <!-- Javascript placed at the end of the document so the pages load faster -->
    <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="css/bootstrap/bootstrap-js/bootstrap.js"></script>
  </body>
</html>


<|start_filename|>index.html<|end_filename|>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="generator" content="pandoc">
    <title>Software Carpentry: Visualizing your data on the web using D3</title>
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-theme.css" />
    <link rel="stylesheet" type="text/css" href="css/swc.css" />
    <link rel="alternate" type="application/rss+xml" title="Software Carpentry Blog" href="http://software-carpentry.org/feed.xml"/>
    <meta charset="UTF-8" />
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>
  <body class="lesson">
    <div class="container card">
      <div class="banner">
        <a href="http://software-carpentry.org" title="Software Carpentry">
          <img alt="Software Carpentry banner" src="img/software-carpentry-banner.png" />
        </a>
      </div>
      <div class="row">
        <div class="col-md-10 col-md-offset-1">
          <h1 class="title">Visualizing your data on the web using D3</h1>

<p>Open science should be visible science. And what better way to make your research visible and accessible than putting it on the internet. But no one wants to read endless tables of data. We’d rather look at graphs, or, even better, have the possibility of interacting with the data. And we have probably all created some graphs. But in order to make them accessible to many people, we will have to move away from our specialized software to a more universal platform - the internet.</p>
<p>We want to:</p>
<ul>
<li>Display our data on a website to increase visibility and accessibility of our research.</li>
</ul>
<p>Our goal is to create a <a href="http://bost.ocks.org/mike/nations/">dynamic bubble plot</a> (a prettier version of a scatter plot) and publish it on the internet.</p>
<p>Along the way, we will learn:</p>
<ul>
<li>how to create our first own web page</li>
<li>how to change the appearance of certain elements on the page</li>
<li>how to integrate graphical elements into our page</li>
<li>how to publish our page</li>
<li>how to allow interaction with elements</li>
<li>how to store data for the use in webpages</li>
<li>how to create a graph in D3</li>
</ul>
<div id="prerequisites" class="prereq panel panel-warning">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-education"></span>Prerequisites</h2>
</div>
<div class="panel-body">
<ul>
<li>Github account and Github client for your operating system (Windows, Linux, iOS).</li>
<li>Participation in at least one SWC workshop.</li>
<li>Familiarity with at least one programming language: concept of loops, functions, and conditionals.</li>
<li>Familiarity with your favorite text editor (Sublime 2 is a good option).</li>
<li>You will need to be comfortable with Google!</li>
<li>Preferably Google Chrome (because of its excellent developer tools).</li>
</ul>
</div>
</div>
<div id="setup" class="prereq panel panel-warning">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-education"></span>Setup</h2>
</div>
<div class="panel-body">
<ul>
<li>It's probably a good idea to install a GitHub client.</li>
</ul>
</div>
</div>
<h2 id="topics">Topics</h2>
<ol style="list-style-type: decimal">
<li><a href="01-html.html">HTML</a></li>
<li><a href="02-css.html">CSS</a></li>
<li><a href="03-images-and-svg.html">Images and SVG</a></li>
<li><a href="04-publishing-with-github.html">Publishing with Github</a></li>
<li><a href="05-javascript.html">JavaScript</a></li>
<li><a href="06-json.html">JSON data format</a></li>
<li><a href="07-d3setup.html">D3 Setup</a></li>
<li><a href="08-d3enter.html">D3 Into the data</a></li>
<li><a href="09-d3exit.html">D3 Add and remove</a></li>
<li><a href="10-d3update.html">D3 Transitions</a></li>
</ol>
<ol start="20" style="list-style-type: lower-roman">
<li><a href="xx-d3future.html">What now?</a></li>
</ol>
<p>We are using <a href="http://gapminder.org">gapminder data</a> and the later lessons are based on an example by <a href="http://bost.ocks.org/mike/nations/"><NAME></a>. In order to make this example slightly easier, we interpolated the data. The data files can be found <a href="https://github.com/IsaKiko/D3-visualising-data/blob/gh-pages/code/nations.json">here</a>. Lessons created by <a href="https://twitter.com/Isa_Kiko"><NAME></a> and <a href="https://twitter.com/robrkerr"><NAME></a>.</p>
        </div>
      </div>
      <div class="footer">
        <a class="label swc-blue-bg" href="http://software-carpentry.org">Software Carpentry</a>
        <a class="label swc-blue-bg" href="https://github.com/swcarpentry/lesson-template">Source</a>
        <a class="label swc-blue-bg" href="mailto:<EMAIL>">Contact</a>
        <a class="label swc-blue-bg" href="LICENSE.html">License</a>
      </div>
    </div>
    <!-- Javascript placed at the end of the document so the pages load faster -->
    <script src="js/jquery.min.js"></script>
    <script src="css/bootstrap/bootstrap-js/bootstrap.js"></script>
  </body>
</html>


<|start_filename|>code/interaction.js<|end_filename|>

var cat_image = document.getElementById('cat_image');
var feed_button = document.getElementById('feed_button');
var run_button = document.getElementById('run_button');

cat_image.onclick = function() {
	alert('Meow!');	
}; 


feed_button.addEventListener("click", feed);
function feed() {
    cat_image.style.width = (cat_image.offsetWidth + 30) + 'px';
};

run_button.addEventListener("click", run);
function run() {
    cat_image.style.width = (cat_image.offsetWidth - 30) + 'px';
};



<|start_filename|>01-html.html<|end_filename|>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="generator" content="pandoc">
    <title>Software Carpentry: HTML</title>
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-theme.css" />
    <link rel="stylesheet" type="text/css" href="css/swc.css" />
    <link rel="alternate" type="application/rss+xml" title="Software Carpentry Blog" href="http://software-carpentry.org/feed.xml"/>
    <meta charset="UTF-8" />
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>
  <body class="lesson">
    <div class="container card">
      <div class="banner">
        <a href="http://software-carpentry.org" title="Software Carpentry">
          <img alt="Software Carpentry banner" src="img/software-carpentry-banner.png" />
        </a>
      </div>
      <div class="row">
        <div class="col-md-10 col-md-offset-1">
          <h1 class="title">HTML</h1>
          <h2 class="subtitle">Making things appear in your browser</h2>
<div id="learning-objectives" class="objectives panel panel-warning">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-certificate"></span>Learning Objectives</h2>
</div>
<div class="panel-body">
<ul>
<li>Create your first web page and view it in a browser</li>
<li>Understand the structure of an HTML document</li>
<li>Understand the different elements within an HTML document</li>
</ul>
</div>
</div>
<p>A way of writing that is understood by all web browsers is HTML: hypertext markup language. Since we don’t have the ability to do logical operations (loops, etc.) with HTML alone, it’s not technically a programming language.</p>
<p>Let’s see how we can get our browser to greet the world. We need to:</p>
<ul>
<li>Create a local folder 'my_first_webpage'</li>
<li>In the folder, create the file 'index.html'</li>
<li>Open the file with a text editor</li>
</ul>
<p>Now, if we want to open our new file in a browser, we have to tell it what kind of file to expect. To do this, we start our file with:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="dt">&lt;!DOCTYPE </span>html<span class="dt">&gt;</span>
<span class="kw">&lt;html&gt;</span>
    --&gt; Everything goes in here <span class="er">&lt;</span>--
<span class="kw">&lt;/html&gt;</span> </code></pre>
<p>Every good webpage consists of a head and a body. The header (&lt;head&gt; to open and &lt;/head&gt; to close) normally contains any meta-data. This could be name of the page or the inclusion of other files.</p>
<p>The body (&lt;body&gt; to open and &lt;/body&gt; to close) is where all our content should go. So everything we type between the brackets will be displayed on our page.</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;head&gt;</span>
<span class="kw">&lt;/head&gt;</span>
<span class="kw">&lt;body&gt;</span>
    Hello world!
<span class="kw">&lt;/body&gt;</span> </code></pre>
<p>Since our browser understands this language, we can instantly open our local index.html file and the browser will interpret our code as visual components.</p>
<p>HTML has more predefined elements that will vary in size and style. To divide the page into different section, we can create a division using &lt;div&gt; to open and &lt;/div&gt; to close it.</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="dt">&lt;!DOCTYPE </span>html<span class="dt">&gt;</span>
<span class="kw">&lt;html&gt;</span>
    <span class="kw">&lt;head&gt;</span>
        --&gt; meta-data (like page title, inclusion of other files) <span class="er">&lt;</span>--
    <span class="kw">&lt;/head&gt;</span>
    <span class="kw">&lt;body&gt;</span>
        <span class="kw">&lt;div&gt;</span>Hello world!<span class="kw">&lt;/div&gt;</span>
        <span class="kw">&lt;div&gt;</span>Hello back!<span class="kw">&lt;/div&gt;</span>
    <span class="kw">&lt;/body&gt;</span>
<span class="kw">&lt;/html&gt;</span> </code></pre>
<div id="other-elements" class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Other elements</h2>
</div>
<div class="panel-body">
<p>Create a folder that contains the file index.html (or download it). What seems to be the difference between &lt;div&gt;, &lt;h1&gt;, and &lt;em&gt;? What about the difference between two &lt;div&gt; elements and two &lt;span&gt; elements? Create a heading that is in italics. Never be afraid to google to find out how to use certain elements and find out about the syntax!</p>
</div>
</div>
<p>Useful resources are also the mozilla developer network (<a href="https://developer.mozilla.org/en-US/">MDN</a>) and <a href="http://www.w3schools.com">w3school</a>.</p>
        </div>
      </div>
      <div class="footer">
        <a class="label swc-blue-bg" href="http://software-carpentry.org">Software Carpentry</a>
        <a class="label swc-blue-bg" href="https://github.com/swcarpentry/lesson-template">Source</a>
        <a class="label swc-blue-bg" href="mailto:<EMAIL>">Contact</a>
        <a class="label swc-blue-bg" href="LICENSE.html">License</a>
      </div>
    </div>
    <!-- Javascript placed at the end of the document so the pages load faster -->
    <script src="js/jquery.min.js"></script>
    <script src="css/bootstrap/bootstrap-js/bootstrap.js"></script>
  </body>
</html>


<|start_filename|>03-images-and-svg.html<|end_filename|>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="generator" content="pandoc">
    <title>Software Carpentry: Images and SVG</title>
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-theme.css" />
    <link rel="stylesheet" type="text/css" href="css/swc.css" />
    <link rel="alternate" type="application/rss+xml" title="Software Carpentry Blog" href="http://software-carpentry.org/feed.xml"/>
    <meta charset="UTF-8" />
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>
  <body class="lesson">
    <div class="container card">
      <div class="banner">
        <a href="http://software-carpentry.org" title="Software Carpentry">
          <img alt="Software Carpentry banner" src="img/software-carpentry-banner.png" />
        </a>
      </div>
      <div class="row">
        <div class="col-md-10 col-md-offset-1">
          <h1 class="title">Images and SVG</h1>
          <h2 class="subtitle">Adding graphical components</h2>
<div id="learning-objectives" class="objectives panel panel-warning">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-certificate"></span>Learning Objectives</h2>
</div>
<div class="panel-body">
<ul>
<li>Adding images to your page</li>
<li>Understanding Scalable Vector Graphics (SVGs)</li>
<li>Adding multiple SVGs to your page</li>
</ul>
</div>
</div>
<p>Websites that only consist of text can be quite boring. So let's have a look at how we can add an image.</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;img</span><span class="ot"> class=</span><span class="st">&#39;image&#39;</span><span class="ot"> src=</span><span class="st">&quot;cat.jpg&quot;</span><span class="kw">&gt;</span></code></pre>
<p>Note that the image element does not need a closing bracket. Having a closing bracket in this case would imply that there could be content between the brackets, which, in the case of an image does not make sense.</p>
<p>If you want to follow along, you will need to download the cat image from our reposotory. Or you can select any other image from your computer.</p>
<p>And by adding a class called 'image' to our CSS file, we can define the size and position of the image we load and apply the style to other images we might want to load.</p>
<pre class="sourceCode css"><code class="sourceCode css"><span class="fl">.image</span> <span class="kw">{</span>
    <span class="kw">width:</span> <span class="dt">200px</span><span class="kw">;</span>
    <span class="kw">position:</span> <span class="dt">relative</span><span class="kw">;</span>
    <span class="kw">left:</span> <span class="dt">20px</span><span class="kw">;</span>
<span class="kw">}</span></code></pre>
<p>The end goal for us is to create a graph, which will be made up of graphical objects such as lines, circles, and squares (not photos of cats). We could just find an image of a circle and use this to represent the data by scaling and positioning it on the page, but that might not be the best way. An image is an inefficient way to represent lines and circles and your webpage would spend an unnecessary amount of time downloading each of these image files.</p>
<p>A better way to include graphical elements that aren't photos, is to use Scalable Vector Graphics (SVGs).</p>
<p>An SVG is just another element in the HTML file, used in the same way as a division.</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;svg</span><span class="ot"> class=</span><span class="st">&quot;chart&quot;</span><span class="kw">&gt;</span>
    <span class="kw">&lt;circle</span><span class="ot"> cx=</span><span class="st">&quot;25&quot;</span><span class="ot"> cy=</span><span class="st">&quot;25&quot;</span><span class="ot"> r=</span><span class="st">&quot;15&quot;</span><span class="ot"> class=</span><span class="st">&quot;circ1&quot;</span><span class="kw">&gt;</span>
    <span class="kw">&lt;/circle&gt;</span>
<span class="kw">&lt;/svg&gt;</span></code></pre>
<p>Here, we've created an SVG canvas, using the styles of the class 'chart'. Within this element, we've created a circle, using the styles of the class 'circ1'. Both of these classes need to also be defined in our CSS file:</p>
<pre class="sourceCode css"><code class="sourceCode css"><span class="fl">.chart</span> <span class="kw">{</span>
    <span class="kw">width:</span> <span class="dt">100px</span><span class="kw">;</span>
    <span class="kw">height:</span> <span class="dt">100px</span><span class="kw">;</span>
<span class="kw">}</span>

<span class="fl">.circ1</span> <span class="kw">{</span>
    <span class="kw">stroke:</span> <span class="dt">green</span><span class="kw">;</span>
    <span class="kw">fill:</span> <span class="dt">white</span><span class="kw">;</span>
    <span class="kw">stroke-width:</span> <span class="dt">5</span><span class="kw">;</span>
<span class="kw">}</span></code></pre>
<p>The circle element is already defined. 'cx', 'cy', and 'r' are attributes that are special to the circle element. 'cx' and 'cy' define the x and y coordinates of the center of the circle, 'r' is the radius of the circle.</p>
<p>But what if we don't want to only use circles, but instead want to use other shapes? On the internet we can find tons of helpful examples. A good resource to find simple examples of using different, commonly used SVG shapes is <a href="http://www.w3schools.com/svg/default.asp">w3school</a>.</p>
<div id="question" class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Question</h2>
</div>
<div class="panel-body">
<p>What happens if 'cx' and 'cy' aren't set?</p>
</div>
</div>
<div id="make-art" class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Make art!</h2>
</div>
<div class="panel-body">
<p>Make some art, using at least one circle, one rectangle, and one polygon. If you don't know what to do, draw a robot!</p>
</div>
</div>
        </div>
      </div>
      <div class="footer">
        <a class="label swc-blue-bg" href="http://software-carpentry.org">Software Carpentry</a>
        <a class="label swc-blue-bg" href="https://github.com/swcarpentry/lesson-template">Source</a>
        <a class="label swc-blue-bg" href="mailto:<EMAIL>">Contact</a>
        <a class="label swc-blue-bg" href="LICENSE.html">License</a>
      </div>
    </div>
    <!-- Javascript placed at the end of the document so the pages load faster -->
    <script src="js/jquery.min.js"></script>
    <script src="css/bootstrap/bootstrap-js/bootstrap.js"></script>
  </body>
</html>


<|start_filename|>06-json.html<|end_filename|>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="generator" content="pandoc">
    <title>Software Carpentry: JSON</title>
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-theme.css" />
    <link rel="stylesheet" type="text/css" href="css/swc.css" />
    <link rel="alternate" type="application/rss+xml" title="Software Carpentry Blog" href="http://software-carpentry.org/feed.xml"/>
    <meta charset="UTF-8" />
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>
  <body class="lesson">
    <div class="container card">
      <div class="banner">
        <a href="http://software-carpentry.org" title="Software Carpentry">
          <img alt="Software Carpentry banner" src="img/software-carpentry-banner.png" />
        </a>
      </div>
      <div class="row">
        <div class="col-md-10 col-md-offset-1">
          <h1 class="title">JSON</h1>
          <h2 class="subtitle">Everything is strings!</h2>
<div id="learning-objectives" class="objectives panel panel-warning">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-certificate"></span>Learning Objectives</h2>
</div>
<div class="panel-body">
<ul>
<li>Understand JavaScript data types</li>
<li>Converting JavaScript data to JSON format</li>
<li>Converting JSON data to JavaScript format</li>
</ul>
</div>
</div>
<p>The goal of these lessons is to visualize data. So far we haven't really dealt with any specific data, let alone relatively big data files. In this lesson, we will learn about the basic data types used by JavaScript and also talk about ways to conveniently convert variables into a text file so we can store it.</p>
<p>There are two containers in JavaScript: arrays (<code>[]</code>-notation) and objects (<code>{}</code>-notation).</p>
<p>In order to create a container, we have to declare it first using the <code>var</code> keyword that we've already come across.</p>
<pre class="js"><code>var list_of_numbers = [];</code></pre>
<p>creates an array. But so far it’s empty.</p>
<p>We can now add elements to this array but instead let's create it again with some values in it, like this:</p>
<pre class="js"><code>var list_of_numbers = [30, 2, 5];</code></pre>
<p>Let's use the console of the browser to look at the values of object by including some extra code:</p>
<pre class="js"><code>console.log(list_of_numbers);</code></pre>
<p>Or we can just address one field of the vector. Counting begins from zero, so the third field has the index '2'.</p>
<pre class="js"><code>console.log(list_of_numbers[2]);</code></pre>
<p><code>list_of_numbers</code> is a vector that holds 3 numbers. We can also have a variable that contains a string:</p>
<pre class="js"><code>var text = &#39;I love cats.&#39;;</code></pre>
<p>We can address this string by using indices, so <code>console.log(text[2])</code> returns <code>l</code>.</p>
<p>Unlike arrays which allow you to access elements using their indices, JavaScript objects allow you to index elements using names. This lets us create something like this:</p>
<pre class="js"><code>var cat_object = {
    weight : 5,
    past_weight_values : [4.5, 5.1, 4.9],
    name : &#39;<NAME>&#39;
};</code></pre>
<div id="creating-new-attributes" class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Creating new attributes</h2>
</div>
<div class="panel-body">
<p>You can append the list of attributes using the dot-syntax <code>cat_object.attributename = ...</code>, (<code>attributename</code> is a placeholder). Create a new attribute <code>height</code> and assign a number!</p>
</div>
</div>
<p>Sometimes we want to have a list of objects that we can address using an index. In our case, we might want to have a list of multiple cats. Now if we want a second cat, we can store them both in the same array <code>cat_list</code>. We can append to an array using the <code>push</code> function:</p>
<pre class="js"><code>var cat_list = [cat_object]; // initializing with the first field being cat_object
cat_list.push({weight : 6 , past_weight_values : [5.9, 5.3, 6.1], name : &#39;Snowball&#39;});</code></pre>
<p>This process is called 'nesting'.</p>
<div id="nesting" class="challenge panel panel-success">
<div class="panel-heading">
<h1><span class="glyphicon glyphicon-pencil"></span>Nesting</h1>
</div>
<div class="panel-body">
<ol style="list-style-type: decimal">
<li>Append a third cat to the array, not entering a name or weight.</li>
<li>Do all animals have to have the same attribute fields?</li>
<li>Use the console of your browser to read the values of your object.</li>
</ol>
</div>
</div>
<div id="object-space-and-name-space" class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Object space and name space</h2>
</div>
<div class="panel-body">
<p>Instead of pushing a new cat to the list, what happens if we initiate the list using cat_object twice?</p>
<p>Reinitialise the list:</p>
<pre class="js"><code>var cat_list2 = [cat_object, cat_object]; </code></pre>
<ol style="list-style-type: decimal">
<li>Change the name of the first cat object <code>cat_list2[0]</code>. Look at the whole list again (<code>cat_list2</code>). What happened?</li>
<li>Look at cat_object. What's going on??</li>
</ol>
</div>
</div>
<p>In Javascript, we have a name space and an object space. The name space contains the names of the variables, the object space contains the actual content. Normally, you would assume that each name points to one object (<code>cat_object.weight</code> --&gt; <code>5</code>, <code>cat_object.name</code> --&gt; '<NAME>'). What we did, when we created our list is that we used three names to point to the same object (<code>cat_list[0]</code>, <code>cat_list[1]</code>, <code>cat_object</code> --&gt; <code>{weight = 5 , past_weight_values = [4.5, 5.1, 4.9], name = '<NAME>'}</code>). When we changed the name of <code>cat_list2[0]</code>, what we actually did was changing the content of the one object <code>cat_object</code> that they were all pointing to.</p>
<p><img src="img/namespace.png" alt="Name space and object space" width="500" /></p>
<p>A good way of creating a new array (as in a new object, not just a new name for the same one) that relates to an array we already have can be done using the <code>map()</code> function.</p>
<p>As an example, we can create a list of dogs that have the same names as our cats, only appended by &quot;Doggie&quot;.</p>
<pre class="js"><code>dog_list = cat_list.map(function(cat) {
    return {
        name: &quot;Doggie &quot;+ cat.name
    };
});</code></pre>
<p>When the map function is called using <code>cat_list.map</code>, it loops through all elements in <code>cat_list</code>, calls each temporarily <code>cat</code>, and creates a new list <code>dog_list</code>, which will have one dog per cat. We join the two strings with a simple <code>+</code>.</p>
<div id="how-much-do-dogs-weigh" class="challenge panel panel-success">
<div class="panel-heading">
<h1><span class="glyphicon glyphicon-pencil"></span>How much do dogs weigh?</h1>
</div>
<div class="panel-body">
<p>Let's assume dogs weigh twice as much as their feline versions. Make the new array reflect this.</p>
</div>
</div>
<p>When we start creating our data for the plot, this is the structured (and nicely annotated) data format that we want. In order to store our variable outside of the scripting environment, we need to convert it into a string.</p>
<p>JavaScript provides an easy way to do this. Variables can get converted from objects/arrays to strings using <code>JSON.stringify()</code>. To convert our list of cats to a string, type</p>
<pre class="js"><code>var cat_json = JSON.stringify(cat_list);</code></pre>
<p>The resulting string is what we would normally store in a <code>.json</code> file to read it in later. At this stage, we can't really create a file, because we're in a browser and creating files would make it too easy to program a virus.</p>
<p>So instead, let's have a look at our stringified variable using the <code>alert()</code> function:</p>
<pre class="js"><code>alert(cat_json);</code></pre>
<p>The output should look like this:</p>
<pre class="out"><code>[{&quot;weight&quot;:5,&quot;past_weight_values&quot;:[4.5,5.2,4.9],&quot;name&quot;:&quot;<NAME>&quot;},{&quot;weight&quot;:6,&quot;past_weight_values&quot;:[5.9,5.3,6.1],&quot;name&quot;:&quot;Snowball&quot;}]</code></pre>
<p>We could now copy this string and save it manually in a <code>.json</code> file.</p>
<div id="de-stringify" class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>De-stringify</h2>
</div>
<div class="panel-body">
<p>Let's assume we read in a JSON formatted string from a file and want to retrieve the nice structure. This process is called parsing and we can use the JSON.parse() function. Convert the variable <code>cat_json</code> back and store it in a container called <code>new_cat_list</code>.</p>
</div>
</div>
<p>We are now at a stage where we can have a look at the data file that we want to work with. Open 'nations.json'.</p>
<p>Here is a snap-shot of our data. We have data from 10 different countries, describing income per capita, population, and life expectancy for different years between 1800 and 2009. Source: <a href="http://www.gapminder.org/data/">gapminder</a></p>
<pre class="out"><code>[
  {
    &quot;name&quot;: &quot;Angola&quot;,
    &quot;region&quot;: &quot;Sub-Saharan Africa&quot;,
    &quot;years&quot;: [
      1950,
      1951,
      1952,
      ...
    ],
    &quot;income&quot;: [
      3363.02,
      3440.9,
      3520.61,
      ...
    ],
    &quot;population&quot;: [
      4117617,
      4173095,
      4232095,
      ...
    ],
    &quot;lifeExpectancy&quot;: [
      29.22,
      29.42,
      29.81,
      ...
    ]
  },
  { ... }
]</code></pre>
        </div>
      </div>
      <div class="footer">
        <a class="label swc-blue-bg" href="http://software-carpentry.org">Software Carpentry</a>
        <a class="label swc-blue-bg" href="https://github.com/swcarpentry/lesson-template">Source</a>
        <a class="label swc-blue-bg" href="mailto:<EMAIL>">Contact</a>
        <a class="label swc-blue-bg" href="LICENSE.html">License</a>
      </div>
    </div>
    <!-- Javascript placed at the end of the document so the pages load faster -->
    <script src="js/jquery.min.js"></script>
    <script src="css/bootstrap/bootstrap-js/bootstrap.js"></script>
  </body>
</html>
