
I received the following question:
I saw the Python code examples to plot GOES-R data provided during the 2021 online training course and I would like to create similar plots using TRMM data. I’m trying to reproduce one of the examples and got some errors. Could you please provide an example script to plot this TRMM NetCDF?
Please find below an example script.
These are the steps I followed:
- Check the available NetCDF datasets using NASA’s Panoply or using the H5Web extension for Visual Studio Code.
- Saw that the precipitation variable is named “TRMM_3B42RT_7_precipitation” and the lat lon bounds are named “lat_bnds” and “lon_bnds”. Also, you may retrieve the time infortation using the “start_time” and “end_time” global attributes.
- Created a custom color map using the reference found here.
| #----------------------------------------------------------------------------------------------------------- | |
| # TRMM (Tropical Rainfall Measuring Mission) - Plotting Example | |
| # Author: Diego Souza | |
| #----------------------------------------------------------------------------------------------------------- | |
| #----------------------------------------------------------------------------------------------------------- | |
| # Required libraries | |
| #----------------------------------------------------------------------------------------------------------- | |
| from netCDF4 import Dataset # Read / Write NetCDF4 files | |
| import matplotlib.pyplot as plt # Plotting library | |
| from datetime import datetime # Basic Dates and time types | |
| import cartopy, cartopy.crs as ccrs # Plot maps | |
| import cartopy.io.shapereader as shpreader # Import shapefiles | |
| import cartopy.feature as cfeature # Common drawing and filtering operations | |
| import numpy as np # Scientific computing with Python | |
| import matplotlib.colors # Matplotlib colors | |
| #----------------------------------------------------------------------------------------------------------- | |
| # Reading the data | |
| #----------------------------------------------------------------------------------------------------------- | |
| # Open the file using the NetCDF4 library | |
| nc = Dataset('trmm_file.nc') | |
| # Extracting the lat lon | |
| min_lat = nc.variables['lat_bnds'][:].min() | |
| max_lat = nc.variables['lat_bnds'][:].max() | |
| min_lon = nc.variables['lon_bnds'][:].min() | |
| max_lon = nc.variables['lon_bnds'][:].max() | |
| # Extract the Brightness Temperature values from the NetCDF | |
| precip = nc.variables['TRMM_3B42RT_7_precipitation'][:] | |
| #----------------------------------------------------------------------------------------------------------- | |
| # Plotting the data | |
| #---------------------------------------------------------------------------------------------------------- | |
| # Choose the plot size (width x height, in inches) | |
| plt.figure(figsize=(10,10)) | |
| # Use the Geostationary projection in cartopy | |
| ax = plt.axes(projection=ccrs.PlateCarree()) | |
| # Define the image extent (plot and outside the plot) | |
| img_extent = [min_lon, max_lon, min_lat, max_lat] | |
| reg_offset = 3 | |
| ax.set_extent([min_lon-reg_offset, max_lon+reg_offset, min_lat-reg_offset, max_lat+reg_offset]) | |
| # Create a custom color scale (reference: https://disc.gsfc.nasa.gov/datasets/TRMM_3B42_Daily_7/summary): | |
| colors = ["#b9d3f1", "#1751bb", "#80e7cd", "#49bd75", "#3d9942", | |
| "#fdf850", "#fed919", "#fb7c07", "#d34800", "#a71d00", | |
| "#932349"] | |
| cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", colors) | |
| cmap.set_under('#b9d3f1') | |
| cmap.set_over('#932349') | |
| vmin = 0 | |
| vmax = 2.5 | |
| # Plot the image | |
| img = ax.imshow(precip, origin='upper', interpolation='bilinear', vmin=vmin, vmax=vmax, extent=img_extent, cmap=cmap) | |
| # Add coastlines, borders and gridlines | |
| ax.coastlines(resolution='10m', color='black', linewidth=0.8) | |
| ax.add_feature(cartopy.feature.BORDERS, edgecolor='black', linewidth=0.5) | |
| gl = ax.gridlines(crs=ccrs.PlateCarree(), color='white', alpha=1.0, linestyle='--', linewidth=0.10, xlocs=np.arange(-180, 180, 5), ylocs=np.arange(-90, 90, 5), draw_labels=True) | |
| gl.top_labels = False | |
| gl.right_labels = False | |
| # Add a background image | |
| land = ax.add_feature(cfeature.LAND) | |
| ocean = ax.add_feature(cfeature.OCEAN, facecolor='dimgrey') | |
| # Add a shapefile | |
| shapefile = list(shpreader.Reader('ne_10m_admin_1_states_provinces.shp').geometries()) | |
| ax.add_geometries(shapefile, ccrs.PlateCarree(), edgecolor='gray',facecolor='none', linewidth=0.3) | |
| # Add a colorbar | |
| plt.colorbar(img, label='Near-Real-Time Precipitation Rate (mm/h)', extend='both', orientation='horizontal', pad=0.05, fraction=0.05) | |
| # Extract start and end date from the global attributes | |
| start_time = nc.getncattr('start_time') | |
| end_time = nc.getncattr('end_time') | |
| # Add a title | |
| plt.title(f'Time Averaged Map of Near-Real-Time Precipitation Rate 3-hourly - {start_time} - {end_time}', fontweight='bold', fontsize=8, loc='left') | |
| #----------------------------------------------------------------------------------------------------------- | |
| # Saving and visualizing the plot | |
| #---------------------------------------------------------------------------------------------------------- | |
| # Save the image | |
| plt.savefig('trmm_img.png', bbox_inches='tight', pad_inches=0, dpi=150 ) | |
| # Show the image | |
| plt.show() |


























































































