Skip to content

Instantly share code, notes, and snippets.

@pbogden
Last active September 9, 2015 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pbogden/4d190c9fa94e6ca59865 to your computer and use it in GitHub Desktop.
Save pbogden/4d190c9fa94e6ca59865 to your computer and use it in GitHub Desktop.
umbc #2

Solution to homework from Class #2

Assignment: Create a bar chart showing the number of earthquakes of magnitude [0 - 1), [1 - 2), [2 - 3), etc. Using data from the USGS real-time earthquake feed.

The idea is to combine what we learned about the USGS API with the bar chart from Mike Bostock's most excellent Let's Make a Bar Chart, the code for which is here. To help get you started, this demo shows how to access and inspect data from the USGS earthquake API.

<!doctype HTML>
<meta charset="utf-8">
<title>umbc2</title>
<style>
.chart div {
font: 10px sans-serif;
background-color: steelblue;
text-align: right;
padding: 3px;
margin: 1px;
color: white;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<body>
<div>
<h1>Open the developer's console...</h1>
</div>
<div class="chart"></div>
<script>
var data; // This is a global. We'll talk about why I defined it here.
var url = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson";
d3.json(url, function(error, quakes) {
if (error) console.log(error);
console.log("Data from USGS:", quakes);
quakes = quakes.features.map(function(d) { return d.properties.mag; }); // Setting the value of the global here.
console.log("Earthquake magnitudes:", quakes);
data = [];
for (var i = 0; i < 10; i++) {
data[i] = quakes.filter(function(d) { return d >= i && d < i + 1; }).length;
}
console.log("Binned data:", data);
// The rest of the code is directly from the example. All we've done is provide a new "data" array
var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, 420]);
d3.select(".chart")
.selectAll("div")
.data(data)
.enter().append("div")
.style("width", function(d) { return x(d) + "px"; })
.text(function(d) { return d; });
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment