Learn data science and machine learning by building real-world projects on Jovian

Earthquakes Visualization (Animation)

import Packages

In [1]:
import pandas as pd
import numpy as np

import plotly.graph_objects as go
import plotly.express as px

Extractors

In [2]:
def subarea_extractor(x):
    return x[0]

def area_extractor(x):
    return x[-1]

Time Manipulator

In [3]:
def fetch_date(time):
    return str(time).split(' ')[0]

def fetch_weekday(time):
    date = fetch_date(time)
    return date + ' - ' + str(time.weekday())

def fetch_hour(time):
    t = str(time).split(' ')
    return t[0] + ' - ' + t[1].split(':')[0]

Data Fetching and Preprocessing

In [4]:
def fetch_quakes_data(manner='daily', bbox='Worldwide', mag_thresh=2):
    url_link = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/{}.csv'
    
    if (manner == 'weekly'):
        data_link = url_link.format('all_week')
    elif (manner == 'monthly'):
        data_link = url_link.format('all_month')
    else:
        data_link = url_link.format('all_day')
    
    eqdf = pd.read_csv(filepath_or_buffer=data_link)
    eqdf = eqdf[['time', 'latitude', 'longitude', 'mag', 'place']]
    
    place_list = eqdf['place'].str.split(', ')
    eqdf['sub_area'] = place_list.apply(func=subarea_extractor)
    eqdf['area'] = place_list.apply(func=area_extractor)
    eqdf = eqdf.drop(columns=['place'], axis=1)
    
    if isinstance(mag_thresh, int) and (mag_thresh > 0):
        eqdf = eqdf[eqdf['mag'] >= mag_thresh]
    else:
        eqdf = eqdf[eqdf['mag'] > 0]
    
    if bbox in eqdf['area'].to_list():
        eqdf = eqdf[eqdf['area'] == bbox]
        max_mag = eqdf['mag'].max()
        center_lat = eqdf[eqdf['mag'] == max_mag]['latitude'].values[0]
        center_lon = eqdf[eqdf['mag'] == max_mag]['longitude'].values[0]
    else:
        center_lat, center_lon = [54, 15]
    
    eqdf['time'] = pd.to_datetime(eqdf['time'])
    
    if (manner == 'weekly'):
        new_col = 'weekday'
        eqdf[new_col] = eqdf['time'].apply(func=fetch_weekday)
    elif (manner == 'monthly'):
        new_col = 'date'
        eqdf[new_col] = eqdf['time'].apply(func=fetch_date)
    else:
        new_col = 'hours'
        eqdf[new_col] = eqdf['time'].apply(func=fetch_hour)
    
    eqdf = eqdf.sort_values(by='time')
    
    return eqdf, center_lat, center_lon

Visualizer

In [5]:
def visualize_quakes_data(manner='daily', bbox='Worldwide', mag_thresh=2):
    eqdf, clat, clon = fetch_quakes_data(manner=manner, bbox=bbox, mag_thresh=mag_thresh)
    
    if (manner == 'monthly'):
        af = 'date'
    elif (manner == 'weekly'):
        af = 'weekday'
    else:
        af = 'hours'
    
    zoom = 3 if bbox != 'Worldwide' else 1
    
    fig = px.scatter_mapbox(
        data_frame=eqdf,
        lat='latitude',
        lon='longitude',
        center=dict(lat=clat, lon=clon),
        size='mag',
        color='mag',
        hover_name='sub_area',
        zoom=zoom,
        mapbox_style='stamen-terrain',
        # color_continuous_scale=px.colors.cyclical.IceFire,
        animation_frame=af,
        title='{} Earthquakes - {}; mag - {}'.format(manner.title(), bbox, mag_thresh)
    )
    
    fig.update_layout(
        margin=dict(l=0, r=0, t=40, b=0)
    )
    
    fig.show()
    return None

Worldwide

Daily Basis

In [6]:
visualize_quakes_data(manner='daily', mag_thresh=None)

Weekly Basis

In [7]:
visualize_quakes_data(manner='weekly', mag_thresh=None)

Montly Basis

In [8]:
visualize_quakes_data(manner='monthly', mag_thresh=None)

Area Based

Daily Basis

In [9]:
visualize_quakes_data(manner='daily', bbox='Alaska', mag_thresh=None)

Weekly Basis

In [10]:
visualize_quakes_data(manner='weekly', bbox='Alaska', mag_thresh=None)

Monthly Basis

In [11]:
visualize_quakes_data(manner='monthly', bbox='Alaska', mag_thresh=None)

End