Mapping USGS Earthquake Data from 2015 to 2025 in Python

Build an end-to-end Python analysis of global USGS earthquake data from 2015 to 2025. Use Pandas, Cartopy, Folium, and DBSCAN to explore seismic patterns.

Mapping USGS Earthquake Data from 2015 to 2025 in Python

Earthquakes are one of the most devastating natural phenomena. According to the U.S. Geological Survey, there are approximately 500,000 detectable earthquakes worldwide each year. About 100,000 can actually be felt by people, and around 100 of these cause some real damage.

In this article, we will use the USGS Earthquake Data, which is a collection of seismic activities monitored, recorded, and reported by the U.S. Geological Survey (USGS) Earthquake Hazards Program, both in the United States and worldwide. We will do an end-to-end data analysis in Python using Pandas, Cartopy, Matplotlib, Seaborn, and Folium to derive patterns of seismic activity throughout the globe.

This is an excellent intermediate-level Python project as it combines real-world scientific data, Pandas, time-series analysis, geospatial visualisation, and anomaly detection. Instead of trying to understand each line of code and the functions used from different libraries, we will focus on how tools from different libraries can be used and implemented to get the required analysis. Let us start with the project:

Setting up the Project & Importing the Libraries

First, let us create the project folder. I will use PyCharm as IDE, and create a new project by the name of “Global Earthquakes Analysis”. Once created, the project will open with a Python file “main.py”. This is where we will be coding the project. Next, go to the terminal and install the required packages using the following line:

Now go to the “main.py” file and start importing the required libraries; some of these we have installed above.

The os Python module lets us create folders and files and manage file paths. The time module provides functions for working with time and delays. We use it to introduce pauses between API requests. Python sometimes displays warnings when it encounters something that might cause unexpected behavior. We import the warnings module so we can control how warnings are displayed. The requests library allows the program to communicate with websites and APIs.

The numpy library allows mathematical calculations and working with numerical arrays. In our project, NumPy also helps create latitude and longitude bins for earthquake density maps. pandas is one of the most important libraries in data analysis. We use Pandas to transform raw earthquake data into a structured dataset.

Next, we have imported matplotlib to convert numerical data into charts and graphs. LogNorm is used to normalize numerical values on a logarithmic scale when creating visualizations. This is particularly useful in our project because earthquake counts can vary significantly across geographic regions, spanning several orders of magnitude. A logarithmic scale makes it easier to visualize both low-activity and high-activity regions without the smaller values becoming visually insignificant.

The Python library seaborn is built on top of Matplotlib. It makes statistical visualizations easier to create and provides attractive default styling. folium and cartopy are two libraries used for geographic visualization. We will see how beautifully they plot the required maps for our project.

pathlib is a built-in Python module for working with file and directory paths. In our project, Path makes it easier to manage where CSV files, PNG maps, and reports are stored.

The datetime module provides tools for working with dates and times. timedelta represents a duration or difference between two dates. Finally, DBSCAN, which stands for “Density-Based Spatial Clustering of Applications with Noise”, is an unsupervised machine learning algorithm. In our project, DBSCAN will help us identify geographical concentrations of earthquake epicenters.

The last line, warnings.filterwarnings("ignore"), tells Python to suppress warning messages.

Project Configuration

Before downloading earthquake data or performing analysis, we establish the time period, magnitude threshold, API address, output folders, visualization style, and API connection. This section defines the project configuration.

First of all, we will define the start and end date START_DATE and END_DATE, setting the timeline of our analysis from 1st January 2015 to 31st December 2025. Next, we are going to set the minimum magnitude of earthquakes MIN_MAGNITUDE to be considered as 2.5. This will help us narrow the analysis to events meeting our chosen criteria instead of including the weakest seismic waves.

Next, we will store the address of the USGS Earthquake Catalog API in the API_URL variable. USGS maintains earthquake records. Our Python program requests those records, and the API returns the information in a structured format.

We will define and then create the required directories. The BASE_DIR variable stores the absolute path to the directory containing the Python file currently being executed. The OUTPUT_DIR will define where our project will save the results. The CHART_DIR creates a path pointing to a charts folder inside output. We will set the background of our charts to “whitegrid” for clean visuals using the Seaborn set_theme() function.

Finally, we’ll create a reusable HTTP session using the Requests library’s Session() method. We’ll also set a custom User-Agent header to "GlobalEarthquakeAnalysis/1.0" using the headers.update() method. This ensures that every request made through our session automatically includes the specified header.

Data Collection

The next step is to collect our required data. We will do this using two functions: fetch_interval() and download_earthquake_data(). The first function fetches earthquake records for a given date interval, while the second downloads data for the entire period, month by month.

Let us go through both these functions:

The fetch_interval(start, end) function takes two inputs, the start and end dates, and displays the date interval currently being downloaded. We will request data in GeoJSON format because it is particularly useful for geographical data. We will specify the date interval, include the minmagnitude, sort earthquake records by occurrence time in ascending order, and set the maximum number of earthquake records returned per request. Once the parameters are set, we send a GET request to the USGS API, passing our parameters dictionary to the API. The API response is stored in the response variable and contains multiple geographical records. We can extract the earthquake records by accessing the value associated with the features key. These records will then be stored in the features variable. We will use a conditional statement to enable data interval splitting if the size reaches the 20,000 limit. To sum up, the above code will return a Python list containing earthquake records retrieved from the USGS API for the specified time interval.

The second function is download_earthquake_data(). It is responsible for downloading earthquake records for the entire period from January 2015 to December 2025. It uses the fetch_interval() function repeatedly to download data month by month and combine everything into one list.

This function will use a while loop and the fetch_interval() function to download the earthquake data one month at a time, collect everything in the all_features list, and keep repeating until 2025 is covered. So by the end of the loop, we will have appended all the months’ records to our all_features list, and our download will be completed.

When the above functions are called, data is fetched and downloaded in intervals, and the process is displayed on the screen for the user:

Data Downloading

Data Downloading (Image by Author)

Converting GeoJSON Data into a Pandas DataFrame

This block now deals with converting the GeoJSON data into a pandas dataframe so we can easily access it for our analysis.

We will first define the function create_dataframe, which takes features as its argument. features refers to the list of earthquake records returned by our download function. We will then create an empty list called records, which will store the cleaned and organized information for every earthquake. We will then loop through every earthquake record one by one to extract its properties like “Magnitude”, “Time”, “Location Description”, etc. that the USGS API stores inside a dictionary called "properties". The .get() method retrieves this information. We also define the longitude, latitude, and depth from the coordinates in properties. Lastly, we will append the earthquake information to the records list. For every earthquake, we create a dictionary containing the information we want to keep. Each dictionary becomes one row, and each key becomes a column. We then create a dataframe from the records list using pandas pd.DataFrame(). We will then display the shape of the dataframe to the user using the pandas df.shape() function, and finally, the function returns the completed DataFrame so we can use it in the next stages of our analysis.

Dataframe Shape

Dataframe Shape (Image by Author)

Cleaning the Dataset

Now that we have downloaded the dataset, we need to make sure the data is accurate and ready for analysis. For this purpose, we will clean the downloaded dataset of duplicate earthquake records, missing information, invalid geographical coordinates, incorrect data types, etc. The clean_data() function, which will take as an argument the dataframe df we created previously, will clean the dataset, create additional columns that will help us analyze earthquake patterns, and save the final dataset as a CSV file.

Now let us go through the above. Because we are cleaning the dataset and making changes, we will make an additional copy of the original dataframe using df.copy(). We will remove duplicate records of the same earthquake using the df.drop_duplicates() and passing the USGS “id” as an argument. This tells Pandas to check duplicates using only the id column. Next, we will remove rows containing missing values using the dropna() function, specifying the columns of importance in our subset=["time", "latitude", "longitude", "magnitude"]. We will then remove invalid coordinates and include the minimum magnitude condition. Next, we will identify columns that should contain numeric values and convert them into numeric data types. This is done to ensure that we can perform mathematical operations and statistical analysis on these later on. To prepare the dataset for deeper analysis, we will extract the date, year, and month from the time column and create additional columns that will help us analyze earthquake patterns over time.

With the dataset cleaned and saved as a CSV file, we are ready to move on to the analysis and visualization stages of the project.