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.
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:
geopandas: Makes working with geographic data easy.
cartopy: For high-quality maps and plotting data on maps.
basemap: Older but useful for map projections and plotting.
jupyterlab: Interactive Python notebooks for running code and visualizing plots.
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.
⚠ 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.
Windows: Press Win + E → Navigate to folder.
Linux: Press Super + E or open Files → Navigate to folder.
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:
Relative Path: If the CSV file is in the same folder as your Python script (e.g., 'earthquakes.csv').
Absolute Path: Full path to the file (recommended for beginners to avoid confusion).
Windows: Right-click the file → Properties → Copy path, then replace single backslashes \ with double \\.
Linux/Mac: Open Terminal and type pwd in the file directory to get the path, then add the file name.
# 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
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:
Changing the map style (different projections like 'cyl', 'ortho' for a globe effect).
Adding colors and adjusting point sizes based on magnitude.
Adding a legend, titles, and a background color to make it visually clear.
Saving the figure as an image (plt.savefig()).
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:
Other countries: Search online for "fault lines shapefile [country name]". Make sure to download the .shp file along with its associated files (.shx, .dbf, etc.).
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)
# --- 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.
# --- 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)
💡 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:
🌐 Global CMT Project – provides moment tensor solutions for worldwide earthquakes.
Step 2: Example CSV Format
Alternatively, you can prepare a CSV file with your own focal mechanism data. Example format:
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
# 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)
Most errors come from typos, missing packages, incorrect paths, or forgetting to activate the environment.
Print intermediate outputs to debug (df.head(), df.dtypes).
✅ 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.
geopandas : facilite la manipulation des données géographiques.
cartopy : pour créer des cartes de haute qualité et y tracer des données.
basemap : ancien mais utile pour les projections cartographiques et le tracé.
jupyterlab : notebooks interactifs pour exécuter du code et visualiser des graphiques.
É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.
Après avoir défini vos paramètres, cliquez sur Rechercher :
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 :
Excel (Windows)
LibreOffice Calc (Linux)
Exemple de données mal alignées :
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 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.
Windows : Appuyez sur Win + E → Naviguez jusqu'au dossier.
Linux : Appuyez sur Super + E ou ouvrez Fichiers → Naviguez jusqu'au dossier.
É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 :
Chemin relatif : si le fichier CSV se trouve dans le même dossier que votre script Python (ex. 'earthquakes.csv').
Chemin absolu : chemin complet vers le fichier (recommandé pour éviter toute confusion pour les débutants).
Exemples de chemins absolus :
Windows : C:\\Users\\VotreNom\\Documents\\earthquakes.csv (utilisez des doubles barres \\)
Windows : Clic droit sur le fichier → Propriétés → Copier le chemin, puis remplacez les barres simples \ par des doubles \\.
Linux/Mac : Ouvrir un terminal et taper pwd dans le dossier contenant le fichier, puis ajouter le nom du fichier.
# 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é
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 :
Changeant le style de la carte (différentes projections comme 'cyl', 'ortho' pour un effet globe).
Ajoutant des couleurs et en ajustant la taille des points selon la magnitude.
Ajoutant une légende, des titres et une couleur de fond pour plus de clarté.
Enregistrant la figure comme image (plt.savefig()).
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 :
Autres pays : Cherchez sur Internet "fault lines shapefile [nom du pays]". Assurez-vous de télécharger le fichier .shp ainsi que les fichiers associés (.shx, .dbf, etc.).
É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
# --- 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 :
Charger un shapefile avec GeoPandas
Extraire et tracer les géométries
Les afficher sur une carte avec Basemap ou Cartopy
💡 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 :
🌐 Global CMT Project – fournit des solutions de tenseurs de moment pour les séismes dans le monde entier.
É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 :
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'])
# 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 :
Visualiser plusieurs mécanismes focaux de séismes stockés dans un CSV
Tracer des beachballs à leurs coordonnées géographiques sur une carte
Utiliser soit Basemap, soit Cartopy pour la visualisation géographique
Combiner avec des lignes de faille ou d'autres données géospatiales pour l'analyse tectonique
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 :
Jeu de Données Exemple – contient des fichiers CSV avec des événements sismiques fictifs et des shapefiles pour les caractéristiques géographiques.
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 :
La plupart des erreurs proviennent de fautes de frappe, de packages manquants, de chemins incorrects ou de l'oubli d'activer l'environnement.
Affichez les résultats intermédiaires pour le débogage (df.head(), df.dtypes).
✅ 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.