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.

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

import plotly.offline aspy_off

from plotly.graph_objs import *

data=[]

data.append(

Scattermapbox(

lon=df_no_nan['lonbin'].values,

lat=df_no_nan['latbin'].values,

mode='markers',

marker=Marker(

color=df_no_nan['anom'].values,

colorscale=colorscale

),

)

)

layout=Layout(

margin=dict(t=0,b=0,r=0,l=0),

autosize=True,

hovermode='closest',

showlegend=False,

mapbox=dict(

accesstoken=mapbox_access_token,

bearing=0,

center=dict(

lat=38,

lon=-94

),

pitch=0,

zoom=0,

style='light'

),

)

fig=dict(data=data,layout=layout)

py_off.plot(fig,filename='Da_Weather_2.html')

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.