SISMOLOGIE ET STRUCTURE INTERNE DU GLOBE Mini-project in Python

👋 Welcome to the Seismic Python Mini Project

This page is a step-by-step guide through a fascinating journey: from learning Python basics, downloading seismic data, and working with shapefiles, to creating maps and beachball diagrams. Whether you're a beginner or an enthusiast, this project is designed to make seismic data analysis interactive and fun. 😊

💡 Note: If you don’t have your own computer, you can still code and run all Python scripts in Google Colab. You just need a Gmail account and an internet connection. All files and notebooks will be saved automatically in your Google Drive.
✅ More explanation and step-by-step guide here: https://tahinaprime.mg/s8/colab.html

0. Install Python and Set Up Environment (Anaconda)

We will use Anaconda to install Python, which simplifies environment and package management for beginners.

✅ Download Anaconda here:

Step 1: Install Anaconda

Step 2: Create a Python environment

It's good practice to create a separate environment for each project. Example: phg

# Create environment with Python 3.11
conda create -n phg python=3.11

# Activate the environment
conda activate phg

Step 3: Install required packages (2 choices)

Inside the activated environment, you can install packages either with conda or pip:

# Option 1 (recommended): Use conda to install packages
conda install geopandas cartopy basemap jupyterlab

# Option 2 (faster / alternative): Use pip to install packages
pip install geopandas cartopy basemap jupyterlab

Why we need these packages:

Step 4: Launch JupyterLab

# Start JupyterLab in the current environment
jupyter lab

✅ Now you have Anaconda installed and a dedicated environment (phg) ready for seismic data analysis. You can choose either conda or pip to install packages inside it.

💡 Tip for beginners: Now that you have JupyterLab running, it’s a great time to strengthen your Python skills. You can learn Python basics, practice coding, and try small examples directly in Jupyter notebooks.

✅ Recommended resource: W3Schools Python Tutorial

1. Download Seismic Data

Go to EIDA WebDC3. Choose:

After setting your parameters, click Search:

Search after setting parameters
Click "Search" after setting date and coordinates

Important: The EIDA WebDC3 interface limits the number of events per search to 801. To avoid missing data, it is recommended to split your search by year (or smaller intervals) and append results. Alternatively, you can use the ISC Bulletin, where the search limit is much higher.

3. Locate and Open CSV in Text Editor

Step 1: Locate your CSV file
Make sure you know where it is saved. Usually in Downloads folder or your chosen location.

Step 2: Open in a text editor (do NOT double-click)
Right-click → Open with → Notepad (Windows) or Text Editor (Linux)

You should see fields separated by ;.

Origin Time;Mag.;Type;Lat.;Long.;Depth;Region
2025-09-04T17:53:08;3.3;m;-26.9;26.75;10;South Africa
2025-09-02T17:46:46;3;m;-25.7;28.74;10;South Africa
2025-09-02T15:27:21;3.7;m;-29.66;18.07;10;South Africa
2025-08-29T17:00:33;4;ml;27.51;52.52;12;Southern Iran
2025-08-27T23:28:56;4.2;m;-27.71;26.83;10;South Africa

4. Read CSV in Python

To read a CSV file in Python, we will use the Pandas library. Make sure the file path is correct. You can use:

Examples of Absolute Paths:

You can find the absolute path by:

# Import Pandas library
import pandas as pd

# ✅ Example 1: Using relative path
df = pd.read_csv('earthquakes.csv', sep=';')

# ✅ Example 2: Using absolute path (Windows)
df = pd.read_csv(r'C:\\Users\\Tahina\\Documents\\earthquakes.csv', sep=';')

# ✅ Example 3: Using absolute path (Linux)
df = pd.read_csv('/home/Tahina/Documents/earthquakes.csv', sep=';')

# Convert 'Origin Time' to datetime
# The 'format' keyword can help if your dates are in a specific format like ISO 8601
df['Origin Time'] = pd.to_datetime(df['Origin Time'], format='%Y-%m-%dT%H:%M:%S')

# Extract columns
times = df['Origin Time']
lat = df['Lat.']
lon = df['Long.']
mag = df['Mag.']

# Sort by time
df = df.sort_values('Origin Time')

✅ Using absolute paths avoids "File not found" errors.
✅ Converting to datetime ensures matplotlib plots real time intervals correctly.
✅ Use the format keyword if your timestamps have a consistent pattern, e.g., ISO 8601 '2025-09-04T17:53:08'.
Alternative without Pandas: You can also use Python's built-in open() and split() to read the CSV.

# Example 1: Origin Time in single column
origin_times = []
latitudes = []
longitudes = []
magnitudes = []

with open('earthquakes.csv', 'r') as f:
    header = f.readline() # skip header
    for line in f:
        row = line.strip().split(';')
        origin_times.append(row[0]) # first column = Origin Time
        latitudes.append(float(row[1])) # second column = Latitude
        longitudes.append(float(row[2])) # third column = Longitude
        magnitudes.append(float(row[3])) # fourth column = Magnitude (if exists)
# Example 2: Date and Time in separate columns (as in ISC Bulletin data)
origin_times = []
latitudes = []
longitudes = []
magnitudes = []

with open('earthquakes_separate.csv', 'r') as f:
    header = f.readline() # skip header
    for line in f:
        row = line.strip().split(';')
        datetime_str = row[0] + ' ' + row[1] # first column = Date, second column = Time
        origin_times.append(datetime_str)
        latitudes.append(float(row[2]))
        longitudes.append(float(row[3]))
        magnitudes.append(float(row[4]))
# Both examples now have separate lists ready for plotting or analysis

✅ The second example reflects the CSV format from the ISC Bulletin data available at https://www.isc.ac.uk/iscbulletin/search/catalogue/.

6. Plot Data on Map + Magnitude vs Time

We'll use Matplotlib with two mapping libraries: Basemap (older, now deprecated but still used in many tutorials) and Cartopy (the modern replacement).

# 💡 Tip for beginners: Basemap and Cartopy both let you draw maps, but Cartopy is more up-to-date and works better with the newest Matplotlib.

✅ You can make your plots look more interesting by:

Basemap Example

# Import the Matplotlib library for plotting graphs
import matplotlib.pyplot as plt
# Import the Basemap toolkit (for maps)
from mpl_toolkits.basemap import Basemap

# --- PLOT EARTHQUAKE LOCATIONS ON A MAP ---
# Create a new figure, size 10x6 inches
plt.figure(figsize=(10, 6))
# Define a Basemap object with Mercator projection, map boundaries, and resolution
m = Basemap(projection='merc', llcrnrlat=-40, urcrnrlat=40, llcrnrlon=-30, urcrnrlon=60, resolution='i')
# Draw coastlines on the map
m.drawcoastlines()
# Draw country borders
m.drawcountries()
# Fill continents with beige and lakes with light blue
m.fillcontinents(color='beige', lake_color='lightblue')
# Draw the background of the map (oceans)
m.drawmapboundary(fill_color='lightblue')

# Convert longitude and latitude values into x, y map coordinates
x, y = m(lon.values, lat.values)
# Plot earthquake points: red color, size based on magnitude, slightly transparent
m.scatter(x, y, c='red', s=mag.values*10, alpha=0.7, label='Earthquakes')
# Add a legend to explain symbols
plt.legend(loc='lower left')
# Add a title to the map
plt.title('Earthquake Locations (Basemap)')
# Display the map
plt.show()

# --- PLOT MAGNITUDE VS TIME ---
# Create a new figure, size 10x4 inches
plt.figure(figsize=(10, 4))
# Plot magnitude vs time as a line with circle markers
plt.plot(times, mag, marker='o', color='blue', label='Magnitude')
# Rotate x-axis labels (time) for readability
plt.xticks(rotation=45)
# Label the axes
plt.xlabel('Time')
plt.ylabel('Magnitude')
# Add a title
plt.title('Magnitude vs Time')
# Show the legend
plt.legend()
# Adjust layout so labels/titles don’t overlap
plt.tight_layout()
# Show the time series plot
plt.show()

Cartopy Example

# Import Matplotlib for plotting
import matplotlib.pyplot as plt
# Import Cartopy coordinate reference systems (CRS)
import cartopy.crs as ccrs
# Import Cartopy features (land, ocean, borders, etc.)
import cartopy.feature as cfeature

# Create a new figure (10x6 inches)
plt.figure(figsize=(10, 6))
# Create an axis with Mercator projection
ax = plt.axes(projection=ccrs.Mercator())
# Set the visible region: lon from -30 to 60, lat from -40 to 40
ax.set_extent([-30, 60, -40, 40])

# Add land colored beige
ax.add_feature(cfeature.LAND, facecolor='beige')
# Add ocean colored light blue
ax.add_feature(cfeature.OCEAN, facecolor='lightblue')
# Add coastlines
ax.add_feature(cfeature.COASTLINE)
# Add country borders (dashed style)
ax.add_feature(cfeature.BORDERS, linestyle=':')

# Plot earthquake points directly using lon/lat, with PlateCarree() projection
plt.scatter(lon.values, lat.values, c='red', s=mag.values*10, alpha=0.7, transform=ccrs.PlateCarree(), label='Earthquakes')
# Add a legend
plt.legend(loc='lower left')
# Add a title
plt.title('Earthquake Locations (Cartopy)')
# Show the map
plt.show()

✅ To change the map region, modify llcrnrlat, urcrnrlat, llcrnrlon, urcrnrlon (e.g., for Asia: -10, 60, 60, 150).
✅ Experiment with other projections like 'ortho' (globe view) or 'cyl' (cylindrical).
🌍 Tip: You can also add a "real map" background:
  • In Basemap: use m.bluemarble() (NASA Blue Marble) or m.shadedrelief().
  • In Cartopy: use built-in imagery like ax.stock_img(), or add map tiles (StamenTerrain(), GoogleTiles(), ESRI()) with add_image().
💡 This makes your earthquake plots look more realistic with terrain/satellite maps as backgrounds.

7. Using GeoPandas to Load and Plot Fault Shapefiles

GeoPandas makes working with shapefiles and geographic data easy. In this example, we'll download a USGS fault shapefile and plot it on a map using both Basemap and Cartopy.

Step 1: Download a Shapefile

You can download fault shapefiles from various sources:

Step 2: Python Example with Basemap

# Import necessary libraries
import geopandas as gpd # for reading shapefiles
import matplotlib.pyplot as plt # for plotting
from mpl_toolkits.basemap import Basemap # for map plotting

# --- LOAD SHAPEFILE ---
shapefile_path = r"C:\\Users\\Tahina\\Documents\\usgs_faults.shp" # Windows path
# shapefile_path = "/home/Tahina/Documents/usgs_faults.shp" # Linux path
faults = gpd.read_file(shapefile_path)

# --- CREATE BASEMAP ---
plt.figure(figsize=(10, 6))
m = Basemap(projection='merc', llcrnrlat=32, urcrnrlat=42, llcrnrlon=-125, urcrnrlon=-114, resolution='i')
m.drawcoastlines()
m.drawcountries()
m.fillcontinents(color='beige', lake_color='lightblue')
m.drawmapboundary(fill_color='lightblue')

# --- PLOT FAULT LINES ---
for _, row in faults.iterrows():
  if row['geometry'].geom_type == 'LineString':
    x, y = m(*row['geometry'].coords.xy)
    m.plot(x, y, color='red', linewidth=1)

# Add title and show map
plt.title('USGS Fault Lines (Basemap)')
plt.show()

Step 3: Python Example with Cartopy

# Import necessary libraries
import geopandas as gpd # for reading shapefiles
import matplotlib.pyplot as plt
import cartopy.crs as ccrs # map projections
import cartopy.feature as cfeature # land, ocean, borders, etc.

# --- LOAD SHAPEFILE ---
shapefile_path = r"C:\\Users\\Tahina\\Documents\\usgs_faults.shp"
faults = gpd.read_file(shapefile_path)

# --- CREATE CARTOPY MAP ---
plt.figure(figsize=(10, 6))
ax = plt.axes(projection=ccrs.Mercator())
ax.set_extent([-125, -114, 32, 42]) # California region

# Add background features
ax.add_feature(cfeature.LAND, facecolor='beige')
ax.add_feature(cfeature.OCEAN, facecolor='lightblue')
ax.add_feature(cfeature.COASTLINE)
ax.add_feature(cfeature.BORDERS, linestyle=':')

# --- PLOT FAULT LINES ---
for _, row in faults.iterrows():
  if row['geometry'].geom_type == 'LineString':
    x, y = row['geometry'].coords.xy
    plt.plot(x, y, transform=ccrs.PlateCarree(), color='red', linewidth=1)

plt.title('USGS Fault Lines (Cartopy)')
plt.show()

✅ These examples show how to:

💡 Tip: Try overlaying your earthquake scatter plots on top of fault lines for deeper analysis. You can also zoom into specific regions by changing the map extent or bounding box.

8. Plotting Seismic Beachballs (Focal Mechanisms)

🌀 Beachballs represent the focal mechanism of earthquakes, showing how the fault slipped and the orientation of the stress. They are essential for understanding earthquake source characteristics and the regional tectonic stress field.

Step 1: Download Focal Mechanism Data

You can download earthquake focal mechanism solutions from:

Step 2: Example CSV Format

Alternatively, you can prepare a CSV file with your own focal mechanism data. Example format:

Origin Time,Latitude,Longitude,Strike,Dip,Rake
2025-09-05T12:30:00,-18.9,47.5,90,30,90
2025-09-06T08:15:00,-19.2,47.8,120,45,85
2025-09-07T22:10:00,-18.5,46.9,60,20,110
2025-09-08T14:05:00,-19.0,47.2,80,35,95

This CSV contains: Origin Time, Latitude, Longitude, and focal mechanism parameters Strike, Dip, Rake in degrees.

Step 3a: Python Example Using Basemap

# Import libraries
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from obspy.imaging.beachball import beach

# Load CSV
df = pd.read_csv('beachballs.csv')
df['Origin Time'] = pd.to_datetime(df['Origin Time'])

# Create Basemap
plt.figure(figsize=(10,6))
m = Basemap(projection='merc', llcrnrlat=-25, urcrnrlat=-12, llcrnrlon=43, urcrnrlon=51, resolution='i')
m.drawcoastlines()
m.drawcountries()
m.fillcontinents(color='beige', lake_color='lightblue')
m.drawmapboundary(fill_color='lightblue')

# Plot beachballs on map
for _, row in df.iterrows():
  x, y = m(row['Longitude'], row['Latitude'])
  b = beach([row['Strike'], row['Dip'], row['Rake']], xy=(x, y), width=2e5)
  b.set_zorder(10)
  plt.gca().add_collection(b)

plt.title('Earthquake Beachballs (Basemap)')
plt.show()

Step 3b: Python Example Using Cartopy

# Import libraries
import pandas as pd
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from obspy.imaging.beachball import beach

# Load CSV
df = pd.read_csv('beachballs.csv')
df['Origin Time'] = pd.to_datetime(df['Origin Time'])

# Create Cartopy map
fig, ax = plt.subplots(figsize=(10,6), subplot_kw={'projection': ccrs.Mercator()})
ax.set_extent([43, 51, -25, -12], crs=ccrs.PlateCarree())
ax.coastlines()
ax.add_feature(cartopy.feature.BORDERS)
ax.add_feature(cartopy.feature.LAND, facecolor='beige')
ax.add_feature(cartopy.feature.OCEAN, facecolor='lightblue')

# Plot beachballs on Cartopy map
for _, row in df.iterrows():
  b = beach([row['Strike'], row['Dip'], row['Rake']], xy=(row['Longitude'], row['Latitude']), width=2e5)
  b.set_zorder(10)
  ax.add_collection(b)

plt.title('Earthquake Beachballs (Cartopy)')
plt.show()

✅ This example demonstrates how to:

9. Explore with Sample Data

Ready to put your skills into practice? We've prepared a collection of sample files to help you experiment and refine your analysis techniques.

📂 Download Sample Data:

Use these datasets to try out different plotting methods, map visualizations, and spatial analyses.

🌍 Want real-world data? You can access seismic datasets from official sources based on your study area:

If you find links for other countries, please share them in the comment section at the bottom of the page.

10. Troubleshooting (Windows & Linux)

This section helps you resolve common problems from installing Anaconda to plotting seismic data.

✅ Always activate your environment (phg) before running scripts.
✅ Restart Jupyter kernel if plots or variables behave unexpectedly.
✅ Print intermediate outputs to verify data and debug issues.

👋 Bienvenue dans le Mini Projet Python en Sismologie

Cette page est un guide étape par étape pour un voyage fascinant : apprendre les bases de Python, télécharger des données sismiques, travailler avec des shapefiles, créer des cartes et des diagrammes beachball. Que vous soyez débutant ou passionné, ce projet est conçu pour rendre l'analyse des données sismiques interactive et amusante. 😊

💡 Note : Si vous n'avez pas votre propre ordinateur, vous pouvez quand même coder et exécuter tous les scripts Python dans Google Colab. Vous avez juste besoin d’un compte Gmail et d’une connexion internet. Tous les fichiers et notebooks seront automatiquement enregistrés dans votre Google Drive.
✅ Plus d'explications et guide étape par étape ici : https://tahinaprime.mg/s8/colab.html

0. Installer Python et configurer l'environnement (Anaconda)

Nous allons utiliser Anaconda pour installer Python, ce qui simplifie la gestion des environnements et des packages pour les débutants.

✅ Téléchargez Anaconda ici :

Étape 1 : Installer Anaconda

Étape 2 : Créer un environnement Python

Il est recommandé de créer un environnement séparé pour chaque projet. Exemple : phg

# Créer un environnement avec Python 3.11
conda create -n phg python=3.11

# Activer l'environnement
conda activate phg

Étape 3 : Installer les packages nécessaires (2 options)

Dans l'environnement activé, vous pouvez installer les packages soit avec conda soit avec pip :

# Option 1 (recommandée) : utiliser conda
conda install geopandas cartopy basemap jupyterlab

# Option 2 (alternative / plus rapide) : utiliser pip
pip install geopandas cartopy basemap jupyterlab

Pourquoi ces packages sont nécessaires :

Étape 4 : Lancer JupyterLab

# Lancer JupyterLab dans l'environnement courant
jupyter lab

✅ Vous avez maintenant Anaconda installé et un environnement dédié (phg) prêt pour l'analyse des données sismiques. Vous pouvez choisir d’installer les packages avec conda ou pip.

💡 Conseil pour les débutants : Maintenant que JupyterLab est lancé, c’est le moment idéal pour renforcer vos compétences en Python. Vous pouvez apprendre les bases, pratiquer et tester de petits exemples directement dans vos notebooks Jupyter.

✅ Ressource recommandée : Tutoriel Python - W3Schools

1. Télécharger les données sismiques

Rendez-vous sur EIDA WebDC3 et choisissez :

Après avoir défini vos paramètres, cliquez sur Rechercher :

Recherche après définition des paramètres
Cliquez sur "Rechercher" après avoir défini la date et les coordonnées

Important : L’interface EIDA WebDC3 limite le nombre d’événements par recherche à 801. Pour éviter de perdre des données, il est recommandé de découper votre recherche par année (ou par intervalles plus petits) et d’assembler les résultats. En alternative, vous pouvez utiliser le Bulletin ISC, où la limite de recherche est beaucoup plus élevée.

2. Copier et coller les données dans Excel ou LibreOffice Calc

Collez les données copiées dans :

Exemple de données mal alignées :

Données mal alignées dans Excel
Données dans Excel avant arrangement des colonnes. Rectangle bleu = en-tête, Rectangle rouge = données (non alignées). ⚠ Pour corriger l'alignement : sélectionnez les cellules, utilisez CTRL+X (couper), puis collez-les dans la colonne correcte.

Après arrangement des données :

Données correctement arrangées dans Excel
Données Excel correctement alignées après collage. L'en-tête (rectangle bleu) et les données (rectangle rouge) sont maintenant correctement dans les colonnes.

💾 Maintenant, sauvegardez le fichier en CSV avec séparateur point-virgule ( ; ). L'utilisation du ; est importante car certaines cellules peuvent contenir des virgules (,) ou des espaces, ce qui casserait la structure des colonnes si vous utilisez une virgule comme séparateur.

3. Localiser et ouvrir le CSV dans un éditeur de texte

Étape 1 : Localisez votre fichier CSV
Assurez-vous de savoir où il est enregistré. Généralement dans le dossier Téléchargements ou l'emplacement choisi.

Étape 2 : Ouvrir dans un éditeur de texte (ne pas double-cliquer)
Clic droit → Ouvrir avec → Notepad (Windows) ou Éditeur de texte (Linux)

Vous devriez voir les champs séparés par un point-virgule (;).

Origin Time;Mag.;Type;Lat.;Long.;Depth;Region
2025-09-04T17:53:08;3.3;m;-26.9;26.75;10;South Africa
2025-09-02T17:46:46;3;m;-25.7;28.74;10;South Africa
2025-09-02T15:27:21;3.7;m;-29.66;18.07;10;South Africa
2025-08-29T17:00:33;4;ml;27.51;52.52;12;Southern Iran
2025-08-27T23:28:56;4.2;m;-27.71;26.83;10;South Africa

4. Lire un CSV en Python

Pour lire un fichier CSV en Python, nous utiliserons la bibliothèque Pandas. Assurez-vous que le chemin du fichier est correct. Vous pouvez utiliser :

Exemples de chemins absolus :

Pour trouver le chemin absolu :

# Importer la bibliothèque Pandas
import pandas as pd

# ✅ Exemple 1 : Utiliser un chemin relatif
df = pd.read_csv('earthquakes.csv', sep=';')

# ✅ Exemple 2 : Utiliser un chemin absolu (Windows)
df = pd.read_csv(r'C:\\Users\\Tahina\\Documents\\earthquakes.csv', sep=';')

# ✅ Exemple 3 : Utiliser un chemin absolu (Linux)
df = pd.read_csv('/home/Tahina/Documents/earthquakes.csv', sep=';')

# Convertir 'Origin Time' en datetime
# L'argument 'format' peut aider si vos dates ont un format spécifique comme ISO 8601
df['Origin Time'] = pd.to_datetime(df['Origin Time'], format='%Y-%m-%dT%H:%M:%S')

# Extraire les colonnes
times = df['Origin Time']
lat = df['Lat.']
lon = df['Long.']
mag = df['Mag.']

# Trier par date
df = df.sort_values('Origin Time')

✅ Utiliser des chemins absolus évite les erreurs "Fichier non trouvé".
✅ Convertir en datetime permet à matplotlib de tracer correctement les intervalles de temps.
✅ Utilisez l'argument format si vos timestamps ont un motif constant, par ex. ISO 8601 '2025-09-04T17:53:08'.
Alternative sans Pandas : Vous pouvez également utiliser les fonctions Python open() et split() pour lire le CSV.

# Exemple 1 : 'Origin Time' dans une seule colonne
origin_times = []
latitudes = []
longitudes = []
magnitudes = []

with open('earthquakes.csv', 'r') as f:
    header = f.readline() # ignorer l'en-tête
    for line in f:
        row = line.strip().split(';')
        origin_times.append(row[0]) # première colonne = Origin Time
        latitudes.append(float(row[1])) # deuxième colonne = Latitude
        longitudes.append(float(row[2])) # troisième colonne = Longitude
        magnitudes.append(float(row[3])) # quatrième colonne = Magnitude (si existante)
# Exemple 2 : Date et Heure dans des colonnes séparées (comme dans les données ISC Bulletin)
origin_times = []
latitudes = []
longitudes = []
magnitudes = []

with open('earthquakes_separate.csv', 'r') as f:
    header = f.readline() # ignorer l'en-tête
    for line in f:
        row = line.strip().split(';')
        datetime_str = row[0] + ' ' + row[1] # première colonne = Date, deuxième colonne = Heure
        origin_times.append(datetime_str)
        latitudes.append(float(row[2]))
        longitudes.append(float(row[3]))
        magnitudes.append(float(row[4]))
# Les deux exemples ont maintenant des listes séparées prêtes pour l'analyse ou le tracé

✅ Le deuxième exemple reflète le format CSV des données du Bulletin ISC disponibles sur https://www.isc.ac.uk/iscbulletin/search/catalogue/.

6. Tracer les données sur une carte + Magnitude en fonction du temps

Nous allons utiliser Matplotlib avec deux bibliothèques de cartographie : Basemap (plus ancienne, maintenant obsolète mais encore présente dans de nombreux tutoriels) et Cartopy (le remplacement moderne).

# 💡 Astuce pour les débutants : Basemap et Cartopy permettent tous les deux de dessiner des cartes, mais Cartopy est plus à jour et fonctionne mieux avec les versions récentes de Matplotlib.

✅ Vous pouvez rendre vos graphiques plus intéressants en :

Exemple avec Basemap

# Importer la bibliothèque Matplotlib pour tracer des graphiques
import matplotlib.pyplot as plt
# Importer l’outil Basemap (pour les cartes)
from mpl_toolkits.basemap import Basemap

# --- TRACER LES SÉISMES SUR UNE CARTE ---
# Créer une nouvelle figure de 10x6 pouces
plt.figure(figsize=(10, 6))
# Définir un objet Basemap avec projection Mercator, limites et résolution
m = Basemap(projection='merc', llcrnrlat=-40, urcrnrlat=40, llcrnrlon=-30, urcrnrlon=60, resolution='i')
# Tracer les côtes
m.drawcoastlines()
# Tracer les frontières des pays
m.drawcountries()
# Colorier les continents en beige et les lacs en bleu clair
m.fillcontinents(color='beige', lake_color='lightblue')
# Colorier l’arrière-plan de la carte (océans)
m.drawmapboundary(fill_color='lightblue')

# Convertir les valeurs longitude/latitude en coordonnées x, y
x, y = m(lon.values, lat.values)
# Tracer les séismes : en rouge, taille selon magnitude, transparence 70%
m.scatter(x, y, c='red', s=mag.values*10, alpha=0.7, label='Séismes')
# Ajouter une légende
plt.legend(loc='lower left')
# Ajouter un titre
plt.title('Localisation des séismes (Basemap)')
# Afficher la carte
plt.show()

# --- TRACER MAGNITUDE EN FONCTION DU TEMPS ---
# Nouvelle figure de 10x4 pouces
plt.figure(figsize=(10, 4))
# Courbe magnitude vs temps avec des cercles
plt.plot(times, mag, marker='o', color='blue', label='Magnitude')
# Rotation des dates pour meilleure lisibilité
plt.xticks(rotation=45)
# Étiquettes des axes
plt.xlabel('Temps')
plt.ylabel('Magnitude')
# Titre du graphique
plt.title('Magnitude en fonction du temps')
# Légende
plt.legend()
# Ajuster la mise en page
plt.tight_layout()
# Afficher le graphique
plt.show()

Exemple avec Cartopy

# Importer Matplotlib
import matplotlib.pyplot as plt
# Importer les systèmes de coordonnées de Cartopy
import cartopy.crs as ccrs
# Importer les éléments (terre, océan, frontières…)
import cartopy.feature as cfeature

# Créer une figure (10x6 pouces)
plt.figure(figsize=(10, 6))
# Créer un axe avec projection Mercator
ax = plt.axes(projection=ccrs.Mercator())
# Zone visible : longitude -30 à 60, latitude -40 à 40
ax.set_extent([-30, 60, -40, 40])

# Terre en beige
ax.add_feature(cfeature.LAND, facecolor='beige')
# Océans en bleu clair
ax.add_feature(cfeature.OCEAN, facecolor='lightblue')
# Côtes
ax.add_feature(cfeature.COASTLINE)
# Frontières en pointillés
ax.add_feature(cfeature.BORDERS, linestyle=':')

# Tracer les séismes avec coordonnées lat/lon, projection PlateCarree()
plt.scatter(lon.values, lat.values, c='red', s=mag.values*10, alpha=0.7, transform=ccrs.PlateCarree(), label='Séismes')
# Légende
plt.legend(loc='lower left')
# Titre
plt.title('Localisation des séismes (Cartopy)')
# Afficher la carte
plt.show()

✅ Pour changer la région affichée, modifiez llcrnrlat, urcrnrlat, llcrnrlon, urcrnrlon (par ex. pour l’Asie : -10, 60, 60, 150).
✅ Expérimentez avec d’autres projections comme 'ortho' (vue globe) ou 'cyl' (cylindrique).
🌍 Astuce : vous pouvez aussi ajouter un fond de carte « réaliste » :
  • Avec Basemap : utilisez m.bluemarble() (NASA Blue Marble) ou m.shadedrelief().
  • Avec Cartopy : utilisez ax.stock_img() ou ajoutez des tuiles de carte (StamenTerrain(), GoogleTiles(), ESRI()) avec add_image().
💡 Cela rend vos cartes de séismes plus réalistes avec un fond satellite/relief.

7. Utiliser GeoPandas pour Charger et Tracer des Fichiers Shapefile de Failles

GeoPandas facilite le travail avec les shapefiles et les données géographiques. Dans cet exemple, nous allons télécharger un shapefile de failles de l’USGS et l’afficher sur une carte en utilisant Basemap et Cartopy.

Étape 1 : Télécharger un Shapefile

Vous pouvez télécharger des shapefiles de failles depuis plusieurs sources :

Étape 2 : Exemple en Python avec Basemap

# Importer les bibliothèques nécessaires
import geopandas as gpd # pour lire les shapefiles
import matplotlib.pyplot as plt # pour tracer
from mpl_toolkits.basemap import Basemap # pour l’affichage cartographique

# --- CHARGER LE SHAPEFILE ---
shapefile_path = r"C:\\Users\\Tahina\\Documents\\usgs_faults.shp" # Exemple Windows
# shapefile_path = "/home/Tahina/Documents/usgs_faults.shp" # Exemple Linux
faults = gpd.read_file(shapefile_path)

# --- CRÉER UNE CARTE AVEC BASEMAP ---
plt.figure(figsize=(10, 6))
m = Basemap(projection='merc', llcrnrlat=32, urcrnrlat=42, llcrnrlon=-125, urcrnrlon=-114, resolution='i')
m.drawcoastlines()
m.drawcountries()
m.fillcontinents(color='beige', lake_color='lightblue')
m.drawmapboundary(fill_color='lightblue')

# --- TRACER LES FAILLES ---
for _, row in faults.iterrows():
  x, y = m(*row['geometry'].coords.xy) # extraire les coordonnées et les convertir
  m.plot(x, y, color='red', linewidth=1) # tracer chaque faille en rouge

# Ajouter un titre et afficher la carte
plt.title('Failles USGS')
plt.show()

Étape 3 : Exemple en Python avec Cartopy

# Importer les bibliothèques nécessaires
import geopandas as gpd
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature

# --- CHARGER LE SHAPEFILE ---
shapefile_path = r"C:\\Users\\Tahina\\Documents\\usgs_faults.shp"
faults = gpd.read_file(shapefile_path)

# --- CRÉER UNE CARTE AVEC CARTOPY ---
fig, ax = plt.subplots(figsize=(10, 6), subplot_kw={'projection': ccrs.PlateCarree()})
ax.set_extent([-125, -114, 32, 42]) # Limites : [lon_min, lon_max, lat_min, lat_max]

ax.add_feature(cfeature.COASTLINE)
ax.add_feature(cfeature.BORDERS)
ax.add_feature(cfeature.LAND, facecolor='beige')
ax.add_feature(cfeature.OCEAN, facecolor='lightblue')

# --- TRACER LES FAILLES ---
faults.plot(ax=ax, transform=ccrs.PlateCarree(), color='red', linewidth=1)

plt.title("Failles USGS (Cartopy)")
plt.show()

✅ Cet exemple montre comment :

💡 Astuce : Vous pouvez superposer vos épicentres de séismes sur ces cartes de failles pour analyser leur alignement.
🌍 Avec Basemap, utilisez m.bluemarble() ou m.shadedrelief() pour un fond réaliste.
🌍 Avec Cartopy, vous pouvez utiliser ax.stock_img() ou des tuiles comme StamenTerrain() ou ESRI().

8. Tracer des Beachballs Sismiques (Mécanismes Focaux)

🌀 Beachballs représentent le mécanisme focal des séismes, montrant comment la faille a glissé et l'orientation des contraintes. Ils sont essentiels pour comprendre les caractéristiques de la source sismique et le champ de contraintes tectoniques régionales.

Étape 1 : Télécharger les données des mécanismes focaux

Vous pouvez télécharger les solutions de mécanismes focaux pour les séismes depuis :

Étape 2 : Exemple de format CSV

Alternativement, vous pouvez préparer un fichier CSV avec vos propres données de mécanismes focaux. Exemple de format :

Origine,Latitude,Longitude,Strike,Dip,Rake
2025-09-05T12:30:00,-18.9,47.5,90,30,90
2025-09-06T08:15:00,-19.2,47.8,120,45,85
2025-09-07T22:10:00,-18.5,46.9,60,20,110
2025-09-08T14:05:00,-19.0,47.2,80,35,95

Ce CSV contient : Origine, Latitude, Longitude, et les paramètres du mécanisme focal Strike, Dip, Rake en degrés.

Étape 3a : Exemple Python avec Basemap

# Importer les bibliothèques
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from obspy.imaging.beachball import beach

# Charger le CSV
df = pd.read_csv('beachballs.csv')
df['Origine'] = pd.to_datetime(df['Origine'])

# Créer une carte Basemap
plt.figure(figsize=(10,6))
m = Basemap(projection='merc', llcrnrlat=-25, urcrnrlat=-12, llcrnrlon=43, urcrnrlon=51, resolution='i')
m.drawcoastlines()
m.drawcountries()
m.fillcontinents(color='beige', lake_color='lightblue')
m.drawmapboundary(fill_color='lightblue')

# Tracer les beachballs sur la carte
for _, row in df.iterrows():
  x, y = m(row['Longitude'], row['Latitude'])
  b = beach([row['Strike'], row['Dip'], row['Rake']], xy=(x, y), width=2e5)
  b.set_zorder(10)
  plt.gca().add_collection(b)

plt.title('Beachballs des Séismes (Basemap)')
plt.show()

Étape 3b : Exemple Python avec Cartopy

# Importer les bibliothèques
import pandas as pd
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from obspy.imaging.beachball import beach

# Charger le CSV
df = pd.read_csv('beachballs.csv')
df['Origine'] = pd.to_datetime(df['Origine'])

# Créer une carte Cartopy
fig, ax = plt.subplots(figsize=(10,6), subplot_kw={'projection': ccrs.Mercator()})
ax.set_extent([43, 51, -25, -12], crs=ccrs.PlateCarree())
ax.coastlines()
ax.add_feature(cartopy.feature.BORDERS)
ax.add_feature(cartopy.feature.LAND, facecolor='beige')
ax.add_feature(cartopy.feature.OCEAN, facecolor='lightblue')

# Tracer les beachballs sur la carte Cartopy
for _, row in df.iterrows():
  b = beach([row['Strike'], row['Dip'], row['Rake']], xy=(row['Longitude'], row['Latitude']), width=2e5)
  b.set_zorder(10)
  ax.add_collection(b)

plt.title('Beachballs des Séismes (Cartopy)')
plt.show()

✅ Cet exemple montre comment :

9. Explorer avec les Données d’Exemple

Prêt à mettre vos compétences en pratique ? Nous avons préparé une collection de fichiers d'exemple pour vous aider à expérimenter et affiner vos techniques d'analyse.

📂 Télécharger les Données d’Exemple :

Utilisez ces jeux de données pour tester différentes méthodes de visualisation, cartes et analyses spatiales.

🌍 Vous voulez des données réelles ? Vous pouvez accéder aux jeux de données sismiques officiels selon votre zone d'étude :

Si vous trouvez des liens pour d’autres pays, merci de les partager dans la section commentaires en bas de la page.

10. Dépannage (Windows & Linux)

Cette section vous aide à résoudre les problèmes courants, de l'installation d'Anaconda à la visualisation des données sismiques.

✅ Activez toujours votre environnement (phg) avant d'exécuter les scripts.
✅ Redémarrez le noyau Jupyter si les graphiques ou variables se comportent de manière inattendue.
✅ Affichez les résultats intermédiaires pour vérifier les données et déboguer les problèmes.

Comments / Commentaires

Please share your thoughts or feedback. / Veuillez partager vos reflexions ou commentaires.