Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Finish the plot task for earthquakes #41

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added average_magnitude_per_year.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions earthquake_data.json

Large diffs are not rendered by default.

37 changes: 28 additions & 9 deletions earthquakes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
# However, we will use a more powerful and simpler library called requests.
# This is external library that you may need to install first.
import requests

import json
import numpy as np

def get_data():
# With requests, we can ask the web service for the data.
Expand All @@ -17,7 +18,7 @@ def get_data():
"maxlongitude": "1.67",
"minlongitude": "-9.756",
"minmagnitude": "1",
"endtime": "2018-10-11",
"endtime": "2024-10-20",
"orderby": "time-asc"}
)

Expand All @@ -27,31 +28,49 @@ def get_data():
# To understand the structure of this text, you may want to save it
# to a file and open it in VS Code or a browser.
# See the README file for more information.
...

data = json.loads(text)
with open('response.json','w') as f:
json.dump(data,f)
# We need to interpret the text to get values that we can work with.
# What format is the text in? How can we load the values?
return ...
return data

def count_earthquakes(data):
"""Get the total number of earthquakes in the response."""
return ...
earthquake_times = data['metadata']['count']
return earthquake_times


def get_magnitude(earthquake):
"""Retrive the magnitude of an earthquake item."""
return ...
mag_list=[]
for item in earthquake:
mag_list.append(item['properties']['mag'])
return mag_list


def get_location(earthquake):
"""Retrieve the latitude and longitude of an earthquake item."""
# There are three coordinates, but we don't care about the third (altitude)
return ...
loc_list=[]
for item in earthquake:
loc_list.append(item['geometry']['coordinates'][:2])
return loc_list


def get_maximum(data):
"""Get the magnitude and location of the strongest earthquake in the data."""
...
earthquake = data['features']
max_mag = np.max([get_magnitude(earthquake)])
max_indices = [i for i, value in enumerate(get_magnitude(earthquake)) if value == max_mag]
if len(max_indices) == 1:
max_loc = get_location(earthquake)[max_indices[0]]
else:
max_loc = []
for index in max_indices:
max_loc.append(get_location(earthquake)[index])
return max_mag, max_loc



# With all the above functions defined, we can now call them and get the result
Expand Down
Binary file added number_per_year.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
118 changes: 118 additions & 0 deletions plot_earthquakes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import os
from datetime import date
import numpy as np

import matplotlib.pyplot as plt
import json
import requests
from jedi.inference.finder import filter_name
from matplotlib.pyplot import pause


def get_data(force_download = False):
"""Retrieve the data we will be working with."""
"if the file is exist, just use the file instead of download"
file_name = 'earthquake_data.json'

if os.path.exists(file_name) and not force_download:
with open(file_name, 'r') as f:
dic = json.load(f)
else:
response = requests.get(
"http://earthquake.usgs.gov/fdsnws/event/1/query.geojson",
params={
'starttime': "2000-01-01",
"maxlatitude": "58.723",
"minlatitude": "50.008",
"maxlongitude": "1.67",
"minlongitude": "-9.756",
"minmagnitude": "1",
"endtime": "2018-10-11",
"orderby": "time-asc"}
)
text = response.text
dic = json.loads(text)
with open(file_name, 'w') as f:
json.dump(dic, f)
return dic


def get_year(earthquake):
"""Extract the year in which an earthquake happened."""
timestamp = earthquake['properties']['time']
# The time is given in a strange-looking but commonly-used format.
# To understand it, we can look at the documentation of the source data:
# https://earthquake.usgs.gov/data/comcat/index.php#time
# Fortunately, Python provides a way of interpreting this timestamp:
# (Question for discussion: Why do we divide by 1000?)
year = date.fromtimestamp(timestamp/1000).year
return year


def get_magnitude(earthquake):
"""Retrive the magnitude of an earthquake item."""
return earthquake["properties"]["mag"]


# This is function you may want to create to break down the computations,
# although it is not necessary. You may also change it to something different.
def get_magnitudes_per_year(earthquakes):
"""Retrieve the magnitudes of all the earthquakes in a given year.

Returns a dictionary with years as keys, and lists of magnitudes as values.
"""

res = {}
for earthquake in earthquakes:
year = get_year(earthquake)
if year in res:
lst = res[year]
else:
lst = []
res[year] = lst
lst.append(get_magnitude(earthquake))
return res


def plot_average_magnitude_per_year(earthquakes):
plt.figure(figsize=(11, 4.8))
dic = get_magnitudes_per_year(earthquakes)
years = []
avgs = []
for year in dic:
years.append(year)
avgs.append(np.mean(dic[year]))

plt.bar(years, avgs)
plt.xlabel("years")
plt.ylabel("magnitude per year")
plt.xticks([i for i in range(np.min(years), np.max(years)+1)])
plt.savefig("average_magnitude_per_year.png")


def plot_number_per_year(earthquakes):
plt.figure(figsize=(11, 4.8))
dic = get_magnitudes_per_year(earthquakes)
years = []
nums = []
for year in dic:
years.append(year)
nums.append(len(dic[year]))

plt.bar(years, nums)
plt.xlabel("years")
plt.ylabel("number per year")
plt.xticks([i for i in range(np.min(years), np.max(years)+1)])
plt.savefig("number_per_year.png")



# Get the data we will work with
quakes = get_data()['features']


# Plot the results - this is not perfect since the x axis is shown as real
# numbers rather than integers, which is what we would prefer!
plot_number_per_year(quakes)
plt.clf() # This clears the figure, so that we don't overlay the two plots
plot_average_magnitude_per_year(quakes)
Loading