Weather maps in Python with Mapbox-gl, xarray, and netcdf4

Climate data is usually stored in netcdf format. The newest netcdf version is called netcdf4. If you want to download climate data from NOAA, for example, you’re going to have to wrestle with the netcdf4 file format.

Luckily, there’s a Python package called xarray that takes scientific datasets like netcdf and converts them into Pandas dataframes… Boom! You can now work with weather data using your favorite Pandas tools and tricks.

This post highlights the key points in going from a real-life netcdf4 file to an interactive map. For the full code walk-through, take a look at this Jupyter notebook on plot.ly.

1. download the data from noaa

The data that we’re going to map is sea surface temperature data from NOAA. You can search and download high resolution netcdf files of sea surface temperature on this NOAA website.

The netcdf file that we’re going to use can be downloaded at this link:

ftp://ftp.cdc.noaa.gov/Datasets/noaa.oisst.v2.highres/sst.day.anom.2017.v2.nc

2. import the NETCDF dataset and convert it to a dataframe

Let’s take a closer look at this.

This line converts a netcdf4 dataset to an xarray dataset.

This line converts the xarray dataset to a Pandas dataframe. Now we’re ready to extract the data we want to map in Pandas.

From here, we use the standard Pandas toolbox to filter and downsample the data. Check out the full Jupyter notebook for the nitty gritty data munging steps in Pandas.

3. map the data

We’ll use mapbox-gl to map the data. Plotly’s open-source Python library has an interface to mapbox-gl, so once you have the latitude and longitude coordinates of your data, mapping is easy. The Python code looks like this:

Plotly writes an offline HTML file called “Da_Weather_2.html” to your disk, which you can open in any browser, attach in an email, embed in your blog, etc.

The resulting plot looks like this:

Global sea temperature on December 16 2017.

 

The advantage of mapbox-gl is that it’s fast. Try zooming into the interactive version to see what we mean. We’re looking forward to adding a Python interface to Mapbox’s new heatmap layer type for even better weather data visualization.

Here’s another interactive netcdf visualization from the same Jupyter notebook:

Visualization of xrray netcdf sample dataset
Visualization of xarray netcdf sample dataset

 

Check out the full Jupyter notebook and share your own maps with us on Twitter.

 

modern.data