Skip to content

Add Cartopy background maps - #107

Merged
cchwala merged 18 commits into
OpenSenseAction:mainfrom
overeem11:AddCartopyMap
Nov 11, 2026
Merged

cchwala merged 18 commits into
OpenSenseAction:mainfrom
overeem11:AddCartopyMap

Conversation

@overeem11

@overeem11 overeem11 commented Sep 23, 2025 •

Copy link
Copy Markdown
Contributor
  • closes #xxxx (Replace xxxx with the GitHub issue number)
  • Tests added and passed if fixing a bug or adding a new feature
  • All code checks from pre-commit passed
  • Added an entry in the CHANGELOG.md file

Summary

This PR adds support for cartopy-based map backgrounds to the poligrain
plotting functions, so that CMLs, points and grids can be plotted on top of
a geographic map.

New features

  • New set_up_axes() helper function in plot_map that creates a
    matplotlib Axes or cartopy GeoAxes with an optional background map:
    • background_map=None: plain matplotlib Axes (previous behavior)
    • background_map="stock": cartopy stock image
    • background_map="OSM": OpenStreetMap tiles
    • background_map="NE": Natural Earth features (ocean, land, lakes,
      borders, coastlines), configurable via the module-level
      DEFAULT_NE_FEATURES dict and the ne_features argument, e.g.
      ne_features={"land": {"facecolor": "green"}}
    • projection and extent arguments to control the map projection and
      the displayed bounding box
  • plot_lines(), plot_plg() and the .plg.plot_cmls() xarray accessors
    (both Dataset and DataArray) now accept the new background_map,
    projection, extent and ne_features arguments and use set_up_axes()
    when no ax is provided
  • scatter_lines() now supports plotting on cartopy GeoAxes via the
    data_crs argument (defaults to PlateCarree for lon-lat data)

Tests

  • Added tests covering set_up_axes (all background map types, extents,
    custom/empty/invalid ne_features), scatter_lines with GeoAxes and
    data_crs validation, plot_lines/plot_plg with GeoAxes and
    ne_features, and the xarray accessors with ne_features
  • All existing tests pass; new code paths are fully covered

Documentation

  • Extended the Plotting notebook with examples for OSM and Natural Earth
    backgrounds, including ne_features customization, for both plot_lines
    and plot_plg
  • Improved docstrings for plot_lines, set_up_axes, plot_plg and the
    .plg.plot_cmls() accessors, documenting all new parameters
  • Added changelog entry

Other

  • Add cartopy as dependency (requires Python >= 3.10)
  • Fix pylint warning C0206 in set_up_axes

@cchwala

cchwala commented Sep 24, 2025

Copy link
Copy Markdown
Member

Here is the code that I used to check if and how LineCollection works togeter with cartopy projection and transformation.

import numpy as np
import cartopy.crs as ccrs

colors = ["indigo", "blue", "green", "yellow", "orange", "red"]

# create a list of half-circles with varying radii
theta = np.linspace(0, np.pi, 36)
radii = np.linspace(4, 5, num=len(colors))
arcs = [np.column_stack([r * np.cos(theta), r * np.sin(theta)]) for r in radii]

ax = plt.axes(projection=ccrs.Geostationary(0))
ax.stock_img()
#ax = plt.axes()
# set axes limits manually because Collections do not take part in autoscaling
#ax.set_xlim(-80, 180)
#ax.set_ylim(-90, 90)
#ax.set_aspect("equal")  # to make the arcs look circular

# create a LineCollection with the half-circles
# its properties can be set per line by passing a sequence (here used for *colors*)
# or they can be set for all lines by passing a scalar (here used for *linewidths*)

line_collection = LineCollection(arcs, colors=colors, linewidths=4, transform=ccrs.PlateCarree())
ax.add_collection(line_collection)

which creates the following image

Bildschirmfoto 2025-09-24 um 14 01 52

This code is a combination of the LineCollection example in the matplotlib docs and an example from the cartopy docs. As discussed offline, it looks as if the transform kwarg is consumed by LineCollection (according to what we saw when changing to different source projection).

@cchwala

cchwala commented Oct 10, 2025 •

Copy link
Copy Markdown
Member

@overeem11 I had a go at integrating some parts of what you have in the separate scatter_lines_background() into the standard scatter_lines() so that plot_lines() does not have to distinguish between the two. Not all features are there, but at least it works now for plotting lines with map background, see the WIP notebook here and the screenshot below.

Bildschirmfoto 2025-10-10 um 09 44 45

Remaining TODOs:

  • allow flexible configuration of NE maps (coastlines, boarders, etc...) which could IMO be best be done with a default dict that is passed as argument and which has the default values that can be adjusted if needed.
  • add same functionality (mainly via the new set_up_axes() helper function) to plot_plg() so that we can also plot the maps as background when plotting points and grids in the same way
  • add same functionality to xarray accessor ploting function

@overeem11 What are crucial feature that are missing in you opinion?

…ebook

I did also refactor the exiting things a bit. This is not perfect yet, though.
Maybe a better solution would be to completely remove the map background stuff
from plot_lines and only have it in plot_plg because plot_lines could be a function
that is not exposed to the user anyway since plot_plg has the same functionality
plus the option to plot grid and points in addition...
@codecov

codecov Bot commented Oct 14, 2025 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.97%. Comparing base (1976175) to head (87e63ae).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #107      +/-   ##
==========================================
+ Coverage   98.90%   98.97%   +0.06%     
==========================================
  Files           7        7              
  Lines         822      878      +56     
==========================================
+ Hits          813      869      +56     
  Misses          9        9              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@cchwala

cchwala commented Oct 14, 2025

Copy link
Copy Markdown
Member

Current status:

  • formating okay
  • old test pass, except for python 3.9

TODOs:

  • add tests
  • clean up notebook
  • maybe implement the remaining features mentioned as TODO above

I will take a break with this PR and try to finish it next week.

this is also the current state in upstream/main but I add it here manually
Make the "NE" (Natural Earth) background map features configurable via a
default dict that users can override, and expose the new background map
options through the xarray accessor plotting functions.

plot_map.py:
- Add DEFAULT_NE_FEATURES dict capturing the default NE features (ocean,
  land, lakes, borders, coastlines). Each entry specifies whether to call
  ax.add_feature or ax.coastlines plus the keyword arguments.
- Add ne_features parameter to set_up_axes. User-provided kwargs are merged
  into the defaults per feature, so individual features can be overridden
  without re-specifying the whole configuration.
- Add ne_features pass-through to plot_lines and plot_plg.
- Clean up redundant parentheses in type annotations (formatter).

xarray.py:
- Expose background_map, projection, and ne_features parameters on both the
  Dataset and DataArray .plg.plot_cmls() accessor methods, forwarding them to
  plot_map.plot_lines.

tests:
- Add tests for custom/empty ne_features, unsupported method error, plot_lines
  with ne_features, plot_plg with ne_features, and both accessor variants.
- Close datasets returned by load_openmrg() in the plot_plg tests. Not closing
  them left netCDF4 file handles open, which caused a segmentation fault when
  the same example files were opened again in a subsequent test.
Expand the docstrings of plot_lines, set_up_axes and plot_plg in plot_map.py to properly document the background_map, projection, extent and ne_features parameters that were added for cartopy background map support. This includes the valid values of background_map ("stock", "OSM", "NE"), the default projection behavior, when the parameters are used (only if ax is not provided), and a Raises section for set_up_axes. Also remove a leftover garbage line in the plot_plg docstring.

Document the same parameters in the docstrings of the plot_cmls accessor methods in xarray.py and clarify that the Dataset accessor plots with a single color while the DataArray accessor colors the lines based on the data values.

Fix pylint warning C0206 (consider-using-dict-items) in set_up_axes by iterating over DEFAULT_NE_FEATURES.items() in the dict comprehension that merges the default and user-provided NE feature configuration.
@cchwala
cchwala merged commit e96f9cc into OpenSenseAction:main Nov 11, 2026
21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants