#!/usr/bin/env python # coding: utf-8 # [![image](https://jupyterlite.rtfd.io/en/latest/_static/badge.svg)](https://demo.leafmap.org/lab/index.html?path=notebooks/52_netcdf.ipynb) # [![image](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/opengeos/leafmap/blob/master/docs/notebooks/52_netcdf.ipynb) # [![image](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/opengeos/leafmap/HEAD) # # **Visualizing NetCDF data** # # Uncomment the following line to install [leafmap](https://leafmap.org) if needed. # In[ ]: # !pip install leafmap # In[ ]: # !pip install xarray rioxarray netcdf4 localtileserver # In[ ]: from leafmap import leafmap # Download a sample NetCDF dataset. # In[ ]: url = "https://github.com/opengeos/datasets/releases/download/raster/wind_global.nc" filename = "wind_global.nc" # In[ ]: leafmap.download_file(url, output=filename, overwrite=True) # Read the NetCDF dataset. # In[ ]: data = leafmap.read_netcdf(filename) data # Convert the NetCDF dataset to GeoTIFF. Note that the longitude range of the NetCDF dataset is `[0, 360]`. We need to convert it to `[-180, 180]` by setting `shift_lon=True` so that it can be displayed on the map. # In[ ]: tif = "wind_global.tif" leafmap.netcdf_to_tif(filename, tif, variables=["u_wind", "v_wind"], shift_lon=True) # Add the GeoTIFF to the map. We can also overlay the country boundary on the map. # In[ ]: geojson = ( "https://github.com/opengeos/leafmap/raw/master/examples/data/countries.geojson" ) # In[ ]: m = leafmap.Map(layers_control=True) m.add_raster(tif, indexes=[1], palette="coolwarm", layer_name="u_wind") m.add_geojson(geojson, layer_name="Countries") m # You can also use the `add_netcdf()` function to add the NetCDF dataset to the map without having to convert it to GeoTIFF explicitly. # In[ ]: m = leafmap.Map(layers_control=True) m.add_netcdf( filename, variables=["v_wind"], palette="coolwarm", shift_lon=True, layer_name="v_wind", indexes=[1], ) m.add_geojson(geojson, layer_name="Countries") m # Visualizing wind velocity. # In[ ]: m = leafmap.Map(layers_control=True) m.add_basemap("CartoDB.DarkMatter") m.add_velocity( filename, zonal_speed="u_wind", meridional_speed="v_wind", color_scale=[ "rgb(0,0,150)", "rgb(0,150,0)", "rgb(255,255,0)", "rgb(255,165,0)", "rgb(150,0,0)", ], ) m # ![](https://i.imgur.com/oL5Mgeu.gif)