Published
Edited
May 10, 2019
Insert cell
Insert cell
md`### Review Exercise #2a
Exercise 2a: Create a histogram of earthquakes based on the [Plotly Bar Chart demo](https://plot.ly/javascript/bar-charts/)`
Insert cell
md`### Answer to Review Exercise #2a
1. Get some earthquake data from [the class demo](https://observablehq.com/@pbogden/earthquakes-on-openlayers) (see the *quakes* cell).`
Insert cell
// Fetch the earthquake data from the USGS GeoJSON feed
quakes = {
let response = await fetch('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_week.geojson');
let json = await response.json();
return json;
}
Insert cell
md`2\\. We want to bin the data according to magnitude. First we'll create an array of bins.`
Insert cell
bins = d3.range(11)
Insert cell
md`3\\. Then we'll count the number of earthquakes in each bin`
Insert cell
counts = {
return bins.map(function(bin) {
let filtered_quakes = quakes.features.filter(d => (d.properties.mag >= bin) && (d.properties.mag < (bin + 1)))
return filtered_quakes.length;
})
}
Insert cell
md`4\\. Copy the code from the Plotly demo and replace "x" and "y" arrays with "bins" and "counts", respectively.`
Insert cell
html`<div id='myDiv'></div>`
Insert cell
{
var data = [
{
x: bins,
y: counts,
type: 'bar'
}
];

Plotly.newPlot('myDiv', data);
}
Insert cell
md`## Review Exercise #2b

Create a scatterplot of magnitude vs depth for earthquakes in the last month. Adapt the [Plotly scatterplot demo](https://plot.ly/javascript/line-and-scatter/) to create the scatterplot.`
Insert cell
md`#### Answer to Exercise #2b

1. Copy and paste the code from the Plotly demo to create the following plot. It's very easy to recreate one of these demos in Observable. In this case, we've removed trace2 and trace3, and left only "trace1", which we've renamed *trace*. And instead of "myDiv", we've called the *id* for this plyt "myDiv2".
`
Insert cell
html`<div id='myDiv2'></div>`
Insert cell
{
var trace = {
x: [1, 2, 3, 4],
y: [10, 15, 13, 17],
mode: 'markers',
type: 'scatter'
};

var data = [trace];

Plotly.newPlot('myDiv2', data);
}
Insert cell
md`2\\. We'll replace the Arrays *x* and *y* with data computed from the earthquake data`
Insert cell
depth = quakes.features.map(d => d.geometry.coordinates[2]) // elements [0] & [1] are Longitude & Latitude
Insert cell
mag = quakes.features.map(d => d.properties.mag)
Insert cell
html`<div id='myDiv3'></div>`
Insert cell
{
var trace = {
x: depth,
y: mag,
mode: 'markers',
type: 'scatter'
};

var data = [trace];

Plotly.newPlot('myDiv3', data);
}
Insert cell
md`### Appendix`
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more