Trying to get away from Basemap for plotting contours on maps, and in particular doing this from a Jupyter notebook, I came across this discussion related to folium: https://github.com/python-visualization/folium/issues/958. Hey! I thought - this is great, let me try it out with ipyleaflet.
The following code gets me close to a working solution, but I see some obscure contours as demonstrated in the image below.
Note: code for reading data is skipped
import matplotlib.pyplot as plt
from ipyleaflet import Map, basemaps, Polygon
# generate matplotlib contours
cs = plt.contourf(lat, lon, val.T) # note transposition to obtain correct coordinate order
# set-up map
zoom = 4
center = [50., 0.]
map = Map(basemap=basemaps.CartoDB.Positron, center=center, zoom=zoom)
# add contours as polygons
# get the pathlines of the contours with cs.allsegs
for clev in cs.allsegs:
polygons = Polygon(
locations=[p.tolist() for p in clev],
color="green",
weight=1,
opacity=0.4,
fill_color="green",
fill_opacity=0.3
)
map.add_layer(polygons);
map
For the image below, I loaded data from ECMWF's ERA-5 reanalysis and plotted horizontal wind speeds in February 2020. Only one contour was selected to demonstrate the problem. The left panel in the figure below shows the plt.contourf(lon, lat, val)
result, which is correct. The panel on the right shows the contour drawn with leaflet. While much of the contour is displayed correctly (please focus only on the lime green area, i.e. the second-highest contour level), there seems to be some issue with ordering of line segments. Does anyone know how this can be fixed?