Skip to content
This repository has been archived by the owner on Oct 25, 2024. It is now read-only.

Add code to find the maxim magnitude in a UK in the 19th century and displaying the plots with earthquake data #17

Open
wants to merge 4 commits into
base: week04
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
63 changes: 63 additions & 0 deletions week04/plot_quakes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import requests
import json
import numpy as np
from datetime import datetime
from matplotlib import pyplot as plt

if __name__ == "__main__":
# ...do things here to find the results...

max_magnitude = 0
coords = {}

# this block of code gets the data of all the earthquakes that occured in UK in the last century (1900-1999)
quakes = 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"}
)



requests_json = json.loads(quakes.text[:])

# a list that stores the magnitude and the time of every earthquake
mag_year = [[item['properties']['mag'],item['properties']['time']] for item in requests_json['features']]

#for every year we create a position in the array. Initially is zero.
# index 0 -- > 2000
# index 1 -- > 2001
#... etc
list_avg_mag = np.zeros(2018 - 2000 + 1)
list_num_quakes = np.zeros(2018 - 2000 + 1)

for year in range(2000,2019):
avg_mag = [] # stores the values of magnitude for an earthquake that happened in a specific year
for item in mag_year:
if int(datetime.utcfromtimestamp(item[1]/1000.0).strftime('%Y')) == year:
avg_mag.append(item[0])
if len(avg_mag) > 0: # some years (2012,2016) have no values and we need to check that
list_avg_mag[year-2000] = np.average(avg_mag)
list_num_quakes[year-2000] = np.sum(avg_mag)

years = [i for i in range(2000,2019)] # the x-axis

plt.plot(years, list_avg_mag, 'ro') # Scattered diagram
plt.xticks(np.arange(min(years), max(years)+1, 1.0)) # the interval in the x axis increases by 1
plt.xlabel("year")
plt.ylabel("average magnitude")
plt.show() # plot the figure

plt.plot(years, list_num_quakes, 'ro')
plt.xticks(np.arange(min(years), max(years)+1, 1.0)) # the interval in the x axis increases by 1
plt.xlabel("year")
plt.ylabel("number of earthquakes")
plt.show() # plot the figure


41 changes: 38 additions & 3 deletions week04/quakes.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""A script to find the biggest earthquake in an online dataset."""

# At the top of the file, import any libraries you will use.
# import ...

import requests
import json
# If you want, you can define some functions to help organise your code.
# def helper_function(argument_1, argument_2):
# ...
Expand All @@ -13,7 +13,42 @@
if __name__ == "__main__":
# ...do things here to find the results...

max_magnitude = 0
coords = {}

# this block of code gets the data of all the earthquakes that occured in UK in the last century (1900-1999)
quakes = requests.get("http://earthquake.usgs.gov/fdsnws/event/1/query.geojson",
params={
'starttime': "1900-01-01",
"maxlatitude": "58.723",
"minlatitude": "50.008",
"maxlongitude": "1.67",
"minlongitude": "-9.756",
"minmagnitude": "1",
"endtime": "1999-12-31",
"orderby": "time-asc"}
)

# We write the above data in a txt file (quake_data.txt)
with open('quake_data.txt', 'w') as target:
target.write(quakes.text[:])

# Then, we read the data from file and we store them to a variable (of type dictionary) named quake_data_dict
with open('quake_data.txt', 'r') as source:
quake_data_dict = json.loads(source.read())

# a loop that compares every earthquake's magnitute with the maximum magnitude
# if miximum magnitude is found, then the max_magnitude and coords variables are updated.
for item in quake_data_dict['features']:
if item['properties']['mag'] == max_magnitude:
coords['coords'].append(item['geometry']['coordinates'][0:2]) # if more than one location exists with the maximum magnitude
elif item['properties']['mag'] > max_magnitude: # if a location has a magnitude bigger than the max_magnitude
coords['coords'] = [item['geometry']['coordinates'][0:2]] #coords is a dictionary so we store the value approprietly
max_magnitude = item['properties']['mag']


# The lines below assume that the results are stored in variables
# named max_magnitude and coords, but you can change that.
print(f"The maximum magnitude is {max_magnitude} "
f"and it occured at coordinates {coords}.")
f"and it occured at coordinates {coords['coords']}.")