Skip to content

tricontourf() doesn't show #594

@lkugler

Description

@lkugler

Hi,
Irregular grids are becoming more and more popular (not lat-lon), so I tried to use tricontourf(), but the plot doesn't show in ultraplot, while it does in mpl.
Maybe you want to take a look what's going on?
Thanks!

Baseline (matplotlib)

I create some simple data.

import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from matplotlib.tri import Triangulation

lats = np.arange(30,60,1)
lons = np.arange(0,30, 1)
llons, llats = np.meshgrid(lons, lats)
data = np.sin(llons) + np.sin(llats)
plt.pcolormesh(llons, llats, data)

1)

This works in matplotlib. I assume that I don't have lat-lon values, so I need to do a triangulation to be able to plot.

def create_triangulation(
    proj: ccrs.Projection,
    lats: np.ndarray,
    lons: np.ndarray,
) -> tuple[Triangulation, np.ndarray]:
    """Create a triangulation and mask for plotting.
    
    Transforms coordinates from PlateCarree to the target projection,
    filters out invalid points, and creates a triangulation.
    
    Args:
        proj: Cartopy projection for coordinate transformation
        lats: Array of latitude values
        lons: Array of longitude values
        
    Returns:
        Tuple of (triangulation, mask)
    """
    xy = proj.transform_points(ccrs.PlateCarree(), lons, lats)
    x = xy[:, 0]
    y = xy[:, 1]

    # depending on the projection, points can fail to be mappable
    mask_valid = np.isfinite(x) & np.isfinite(y)
    if not np.all(mask_valid):
        print(f"Number of invalid points, not projectable onto the map: {np.sum(~mask_valid)}")
        x = x[mask_valid]
        y = y[mask_valid]
    
    triang = Triangulation(x, y)
    return triang, mask_valid


proj = ccrs.Robinson()

lats1d = llats.ravel()
lons1d = llons.ravel()
data1d = data.ravel()

triang, mask = create_triangulation(proj, lats1d, lons1d)

fig = plt.figure(figsize=(5,3))
ax = fig.add_subplot(111, projection=proj)
ax.tricontourf(triang, data1d[mask])
ax.gridlines()
ax.set_global()

Result:
Image

2)

With ultraplot it also works, with lat-lon data:

import ultraplot as pplt

fig, axs = pplt.subplots(ncols=1, nrows=1, refwidth=5, proj=proj) 

h = axs[0,0].pcolor(lons, lats, data)
axs.format(lonlabels="t", latlabels="l",)
fig.colorbar(h, loc="b", )
plt.show()
Image

3)

But now with tricontourf (like in mpl above):

fig, axs = pplt.subplots(ncols=1, nrows=1, refwidth=5, proj=proj) 
h = axs[0,0].tricontourf(triang, data1d[mask])
axs.format(lonlabels="t", latlabels="l",)
fig.colorbar(h, loc="b", )
plt.show()
Image

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions