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

Explore and analyze the earthquake data #11

Open
wants to merge 2 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
39 changes: 32 additions & 7 deletions earthquakes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# 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

def get_data():
# With requests, we can ask the web service for the data.
Expand All @@ -23,39 +23,64 @@ 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
data = response.json()
# 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.
...

# 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 data['metadata']['count']


def get_magnitude(earthquake):
"""Retrive the magnitude of an earthquake item."""
return ...
return earthquake['properties'].get('mag', None) #avoid keyError if mag is not exist


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 ...
coordinates = earthquake['geometry'].get('coordinates',[])
if len(coordinates) >= 2:
return coordinates[0], coordinates[1]
else:
return None, None


def get_maximum(data):
"""Get the magnitude and location of the strongest earthquake in the data."""
...
max_earthquake = []
max_mag = float('-inf')
max_loc = []
for earthquake in data['features']:
mag = get_magnitude(earthquake)
if mag is not None:
if mag > max_mag:
max_mag = mag
max_earthquake = [earthquake]
elif mag == max_mag:
max_earthquake.append(earthquake)

if max_earthquake:
for earthquake in max_earthquake:
max_loc.append(get_location(earthquake)[:2])
return max_mag, max_loc
else:
return None, None



# With all the above functions defined, we can now call them and get the result
data = get_data()
with open('xtfile.json','w',encoding='utf-8') as f:
json.dump(data,f)
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}")
89 changes: 89 additions & 0 deletions plotGraph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
from datetime import date

import matplotlib.pyplot as plt
import pandas as pd
import json
import numpy as np

def get_data():
with open("xtfile.json","r") as f:
data = json.load(f)

return data



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'].get('mag', None)


# 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.
"""
magnitudes_per_year = {}
for earthquake in earthquakes:
if(magnitudes_per_year.__contains__(get_year(earthquake))):
magnitudes_per_year[get_year(earthquake)].append(get_magnitude(earthquake))
else:
magnitudes_per_year[get_year(earthquake)]=[get_magnitude(earthquake)]
return magnitudes_per_year

def plot_average_magnitude_per_year(earthquakes):

data = get_magnitudes_per_year(earthquakes)
average_magnitude=[]
for key in data:
average_magnitude.append(sum(data[key])/len(data[key]))
x = data.keys()
y = average_magnitude
plt.plot(x,y)
plt.xticks(range(min(x),max(x)+1),rotation=-45)
plt.title("average magnitude per year")
plt.xlabel("year")
plt.ylabel("magnitude")


def plot_number_per_year(earthquakes):
data = get_magnitudes_per_year(earthquakes)
average_number=[]
for key in data:
average_number.append(len(data[key]))
x = data.keys()
y = average_number
plt.bar(x,y)
plt.xticks(range(min(x),max(x)+1),rotation=-45)
plt.title("number per year")
plt.xlabel("year")
plt.ylabel("number")


# 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!
plt.subplot(2, 1, 1)
plot_number_per_year(quakes)

plt.subplot(2, 1, 2)
plot_average_magnitude_per_year(quakes)

plt.subplots_adjust(hspace=1)
1 change: 1 addition & 0 deletions xtfile.json

Large diffs are not rendered by default.