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

Earthquake plots #26

Open
wants to merge 5 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
83 changes: 72 additions & 11 deletions earthquakes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@
# 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 matplotlib.pyplot as plt
import datetime
import numpy as np



def get_data():
Expand All @@ -23,39 +28,95 @@ def get_data():

# The response we get back is an object with several fields.
# The actual contents we care about are in its text field:
text = response.text
# 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 = response.json()

with open("response.json", "w") as f:
json.dump(data, f, indent=4)

# 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 ...


return len(data['features'])


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


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 ...
return earthquake['geometry']['coordinates'][:2]


def get_maximum(data):
"""Get the magnitude and location of the strongest earthquake in the data."""
...
max_magnitude = 0
max_locations = []
for earthquake in data['features']:
magnitude = get_magnitude(earthquake)
if magnitude > max_magnitude:
max_magnitude = magnitude
max_locations = [get_location(earthquake)]
elif magnitude == max_magnitude:
max_locations.append(get_location(earthquake))
return max_magnitude, max_locations

def freq_per_yr_plot(plot=False):

years_sec = [earthquake['properties']['time'] for earthquake in data['features']]
years = [datetime.datetime.fromtimestamp(year/1000).year for year in years_sec]

year_counts = {}
for year in years:
if year in year_counts:
year_counts[year] += 1
else:
year_counts[year] = 1
if plot:
plt.bar(year_counts.keys(), year_counts.values())
plt.xticks(np.arange(2000, 2019, 1))
plt.xlabel("Year")
plt.ylabel("Number of Earthquakes")
plt.title("Number of Earthquakes per Year")
plt.show()
return year_counts

def avg_mag_per_year(data, plot=False):
cum_mag_per_year = {}
quakes = [quake for quake in data['features']]
for quake in quakes:
quake_year = datetime.datetime.fromtimestamp(quake['properties']['time']/1000).year
quake_mag = quake['properties']['mag']
if quake_year not in cum_mag_per_year.keys():
cum_mag_per_year[quake_year] = quake_mag
else:
cum_mag_per_year[quake_year] += quake_mag
year_counts = freq_per_yr_plot()
for year in cum_mag_per_year:
cum_mag_per_year[year] = cum_mag_per_year[year]/year_counts[year]
if plot:
plt.bar(cum_mag_per_year.keys(), cum_mag_per_year.values())
plt.xticks(np.arange(2000, 2019, 1))
plt.xlabel("Year")
plt.ylabel("Average Magnitude")
plt.title("Average Magnitude of Earthquakes per Year")
plt.show()
return cum_mag_per_year


# With all the above functions defined, we can now call them and get the result
data = get_data()
print(f"Loaded {count_earthquakes(data)}")
max_magnitude, max_location = get_maximum(data)
print(f"The strongest earthquake was at {max_location} with magnitude {max_magnitude}")
print(f"The strongest earthquake was at {max_location} with magnitude {max_magnitude}")

freq_per_yr_plot(plot=True)
avg_mag_per_year(data, plot=True)
Loading