Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
exclude: ^docs/(gallery|assets)/
exclude: ^(docs/(gallery|assets)/|src/nicefigs/_data/)
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.15.0
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ to [Semantic Versioning](https://semver.org/).

### Added

- Maps work offline: the Natural Earth 110m and 50m coastline, land, ocean and land-border shapefiles
are bundled and used before cartopy would download them, never overriding `cartopy.config`.
`cache_natural_earth(path=None)` (also `python -m nicefigs.naturalearth`) pre-downloads every layer
including 10m; `$NICEFIGS_NATURAL_EARTH_DIR` names the folder searched and written.
- `hatch_region(..., style="dots")` stipples without a hatch outline; `hatch` defaults per style and
`edgecolor="none"` draws no outline. Gallery example `36_stippled_difference_map`.
- Concept-figure primitives in `nicefigs.schematic`: `schematic_axes` (a figure of the printed size
whose data units are inches), `numbered_disc`, `group_band`, `label_pair`, `grid_cells`,
`folder_icon` and the colour helpers `tint`, `shade` and `soft_color`. They draw with the active
Expand Down
4 changes: 4 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ and the [Gallery](gallery.md) for runnable examples.

::: nicefigs.maps

## `nicefigs.naturalearth`

::: nicefigs.naturalearth

## `nicefigs.images`

::: nicefigs.images
Expand Down
Binary file added docs/assets/guide/maps-stipple.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions docs/gallery.md
Original file line number Diff line number Diff line change
Expand Up @@ -490,3 +490,15 @@ from the active theme and the `NICE_COLORS`.
```python
--8<-- "examples/35_schematic.py"
```

### 36 — Difference map with significance stippling {#stippled-difference-map}

[`hatch_region`][nicefigs.hatch_region] with `style="dots"` stipples the cells where a
difference is significant: dots only, no hatch outline, so the diverging colours underneath
stay readable.

![Stippled difference map](gallery/36_stippled_difference_map.png)

```python
--8<-- "examples/36_stippled_difference_map.py"
```
Binary file added docs/gallery/36_stippled_difference_map.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
50 changes: 50 additions & 0 deletions docs/guide/maps.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,56 @@ nf.inset_histogram_colorbar(ax, values, cmap="inferno", bounds=(0.08, 0.55, 0.4,

![Inset histogram colorbar](../assets/guide/maps-inset-hist.png)

## Stippling significance

[`hatch_region()`][nicefigs.hatch_region] marks the cells where a mask is set and leaves the
colours beneath visible. `style="hatch"` (default) draws diagonal lines with an outline;
`style="dots"` draws dots only, with no line along the region's edge, the usual way to
show where a difference is significant. `edgecolor` colours the marks and `hatch` overrides
the pattern:

```python
import numpy as np

import nicefigs as nf
from nicefigs import data

nf.set_theme("paper")

extent = (-12, 40, 34, 60)
lon, lat, diff = data.regional_grid(res=0.25, extent=extent)
fig, ax, _ = nf.map(
lon, lat, diff, extent=extent, projection="platecarree",
diverging=True, inset_hist=False, cbar=True, borders=True,
colorbar_label="model difference [K]",
)
nf.hatch_region(
ax, lon.ravel(), lat.ravel(), (np.abs(diff) > 0.12).ravel(),
style="dots", bin_deg=0.5,
)
```

![Stippled difference map](../assets/guide/maps-stipple.png)

## Working offline

Cartopy downloads its Natural Earth coastlines on first use, which fails without internet
(compute nodes). nicefigs bundles the 110m and 50m coastline, land, ocean and land-border
shapefiles and points cartopy at them whenever a map is drawn. Data cartopy already finds
through `cartopy.config` or `CARTOPY_DATA_DIR` is used first; the bundled data is only the
fallback before a download. For the 10m resolution, cache everything once on a machine with
internet access:

```bash
python -m nicefigs.naturalearth /path/to/natural_earth # or nicefigs.cache_natural_earth(path)
export NICEFIGS_NATURAL_EARTH_DIR=/path/to/natural_earth # on the offline machine
```

`NICEFIGS_NATURAL_EARTH_DIR` is searched after cartopy's own directories and before the
bundled data, and is the default target of
[`cache_natural_earth()`][nicefigs.naturalearth.cache_natural_earth]. The Natural Earth data is in the
public domain.

## Ternary maps

For a three-part composition per point, such as land-use fractions,
Expand Down
39 changes: 39 additions & 0 deletions examples/36_stippled_difference_map.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""Difference map with significance stippling.

A diverging regional difference map; ``hatch_region(..., style="dots")`` stipples the
cells where the difference is significant, with dots only and no outline, so the colours
underneath stay readable.
"""

import numpy as np

import nicefigs as nf
from nicefigs import data


def make():
nf.set_theme("paper")
lon, lat, diff = data.regional_grid(res=0.25, extent=(-12, 40, 34, 60))
significant = np.abs(diff) > 0.12
fig, ax, _ = nf.map(
lon,
lat,
diff,
extent=(-12, 40, 34, 60),
projection="platecarree",
diverging=True,
inset_hist=False,
cbar=True,
borders=True,
colorbar_label="model difference [K]",
title="Difference, stippled where significant",
)
nf.hatch_region(ax, lon.ravel(), lat.ravel(), significant.ravel(), style="dots", bin_deg=0.5)
return fig


if __name__ == "__main__":
import matplotlib

matplotlib.use("Agg")
nf.save(make(), "36_stippled_difference_map", formats=("png", "pdf"))
2 changes: 2 additions & 0 deletions src/nicefigs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
scatter_map,
tri_map,
)
from .naturalearth import cache_natural_earth
from .palettes import (
CATEGORICAL,
CUSTOM_CMAPS,
Expand Down Expand Up @@ -281,6 +282,7 @@
"cross_section",
"cross_section_panels",
"profile",
"cache_natural_earth",
"hatch_region",
"taylor",
"hovmoller",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
UTF-8
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.017453292519943295]]
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
UTF-8
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.017453292519943295]]
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
1 change: 1 addition & 0 deletions src/nicefigs/_data/natural_earth/physical/ne_110m_land.cpg
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
UTF-8
Binary file not shown.
1 change: 1 addition & 0 deletions src/nicefigs/_data/natural_earth/physical/ne_110m_land.prj
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.017453292519943295]]
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
UTF-8
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.017453292519943295]]
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
1 change: 1 addition & 0 deletions src/nicefigs/_data/natural_earth/physical/ne_50m_land.cpg
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
UTF-8
Binary file not shown.
1 change: 1 addition & 0 deletions src/nicefigs/_data/natural_earth/physical/ne_50m_land.prj
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]
Binary file not shown.
Binary file not shown.
1 change: 1 addition & 0 deletions src/nicefigs/_data/natural_earth/physical/ne_50m_ocean.cpg
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
UTF-8
Binary file not shown.
1 change: 1 addition & 0 deletions src/nicefigs/_data/natural_earth/physical/ne_50m_ocean.prj
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]
Binary file not shown.
Binary file not shown.
48 changes: 38 additions & 10 deletions src/nicefigs/maps.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ def _try_cartopy() -> ModuleType | None:
try:
import cartopy.crs as ccrs

from .naturalearth import use_offline_natural_earth

use_offline_natural_earth()
return ccrs
except ImportError:
return None
Expand Down Expand Up @@ -150,6 +153,10 @@ def draw_background(
return
import cartopy.feature as cfeature

from .naturalearth import use_offline_natural_earth

use_offline_natural_earth()

def _rasterize(artist: Any) -> None:
if artist is not None and hasattr(artist, "set_rasterized"):
artist.set_rasterized(True)
Expand Down Expand Up @@ -209,6 +216,9 @@ def _land_mask(nx: int, ny: int, bin_deg: float, resolution: str) -> np.ndarray
from shapely.prepared import prep
except ImportError:
return None
from .naturalearth import use_offline_natural_earth

use_offline_natural_earth()
shp = natural_earth(resolution=resolution, category="physical", name="land")
land = prep(unary_union(list(Reader(shp).geometries())))
lon_c = -180.0 + bin_deg * (np.arange(nx) + 0.5)
Expand Down Expand Up @@ -278,55 +288,73 @@ def _bin_values(
return lon_edges, lat_edges, np.ma.masked_invalid(grid)


_HATCH_STYLES = {"hatch": "////", "dots": "..."}


def hatch_region(
ax: Axes,
lon: ArrayLike,
lat: ArrayLike,
mask: ArrayLike,
*,
ccrs: ModuleType | None = None,
hatch: str = "////",
style: str = "hatch",
hatch: str | None = None,
edgecolor: str = "#333333",
linewidth: float = 0.5,
bin_deg: float = 2.0,
threshold: float = 0.5,
) -> QuadContourSet:
"""Hatch the region where a per-point mask is set, leaving the colours beneath visible.
"""Hatch or stipple the region where a per-point mask is set, leaving the colours beneath visible.

The mask is bin-averaged onto a ``bin_deg`` grid and cells at or above
``threshold`` are hatched without fill.
``threshold`` are marked without fill. ``style="dots"`` gives significance
stippling: dots only, with no line along the region's outline.

Args:
ax: Map axes.
lon: Point longitudes in degrees east.
lat: Point latitudes in degrees north.
mask: Per-point boolean or fraction, same shape as ``lon``.
ccrs: The ``cartopy.crs`` module when ``ax`` is projected, else ``None``.
hatch: Matplotlib hatch pattern.
edgecolor: Hatch colour.
linewidth: Hatch line width in points.
ccrs: The ``cartopy.crs`` module; detected from ``ax`` if ``None``.
style: ``"hatch"`` (diagonal lines, outlined) or ``"dots"`` (dots, never outlined).
hatch: Matplotlib hatch pattern; defaults to ``"////"`` for ``"hatch"`` and ``"..."``
for ``"dots"``.
edgecolor: Colour of the hatch marks. ``"none"`` draws no outline and takes the mark
colour from ``rcParams["hatch.color"]``.
linewidth: Hatch line and outline width in points.
bin_deg: Grid cell size in degrees.
threshold: Minimum cell-mean mask value that is hatched.

Returns:
The contour set drawing the hatch.
"""
if style not in _HATCH_STYLES:
raise ValueError(f"style must be one of {sorted(_HATCH_STYLES)}, got {style!r}")
if hatch is None:
hatch = _HATCH_STYLES[style]
outline = style == "hatch" and edgecolor != "none"
lon = np.asarray(lon, dtype=float)
lat = np.asarray(lat, dtype=float)
m = np.asarray(mask, dtype=float)
lon_e, lat_e, grid = _bin_values(lon, lat, m, bin_deg, 0, False, "110m")
lon_c = 0.5 * (lon_e[:-1] + lon_e[1:])
lat_c = 0.5 * (lat_e[:-1] + lat_e[1:])
filled = np.ma.filled(grid, 0.0)
if ccrs is None and hasattr(ax, "projection"):
ccrs = _try_cartopy()
kw = {}
if ccrs is not None:
kw["transform"] = ccrs.PlateCarree()
cs = ax.contourf(lon_c, lat_c, filled, levels=[threshold, 1e9], colors="none", hatches=[hatch], **kw)
# Without an outline matplotlib colours hatch marks from rcParams, read at creation.
rc = {} if edgecolor == "none" else {"hatch.color": edgecolor}
with plt.rc_context(rc):
cs = ax.contourf(lon_c, lat_c, filled, levels=[threshold, 1e9], colors="none", hatches=[hatch], **kw)
# matplotlib < 3.8 exposes per-level ``.collections``; later the ContourSet is the collection.
targets = getattr(cs, "collections", None) or [cs]
for coll in targets:
coll.set_edgecolor(edgecolor)
coll.set_linewidth(linewidth)
coll.set_edgecolor(edgecolor if outline else "none")
coll.set_linewidth(linewidth if outline else 0.0)
return cs


Expand Down
Loading
Loading