Skip to content

Conversation

Illviljan
Copy link
Contributor

@Illviljan Illviljan commented Jul 24, 2025

Contour and contourf does some strange things when norm is changed from the defaults. Using a logarithmic norm is not uncommon.
It seems better to let matplotlib handle most of the default values.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm

import xarray as xr


# %%
N = 100
x = np.linspace(-3, 3, N)
y = np.linspace(-2, 2, N)

X, Y = np.meshgrid(x, y)

Z1 = np.exp(-(X**2) - Y**2)
Z2 = np.exp(-((X * 10) ** 2) - (Y * 10) ** 2)

Z = Z1 + 50 * Z2

vmin = Z.min()
vmax = Z.max()
norm = LogNorm(vmin=vmin, vmax=vmax)


# %% xarray
da_z = xr.DataArray(data=(Z), coords=dict(x=("x", x), y=("y", y)))

fig, axs = plt.subplots(2, 3, layout="constrained")

for i, plotfunc in enumerate(("pcolormesh", "contourf", "contour")):
    p = getattr(da_z.plot, plotfunc)
    p(x="x", y="y", ax=axs[0, i], vmin=vmin, vmax=vmax, add_colorbar=True)
    axs[0, i].set(title=f"{plotfunc} linear")
    p(x="x", y="y", ax=axs[1, i], norm=norm, add_colorbar=True)
    axs[1, i].set(title=f"{plotfunc} log")

PR:
image

Main:
image

@Illviljan Illviljan changed the title Remove default re-definition Use better contour defaults with logarithmic norms Jul 24, 2025
@Illviljan Illviljan marked this pull request as ready for review July 24, 2025 13:29
@Illviljan
Copy link
Contributor Author

This is ready for review!
Would be nice if a frequent user of contour tries it out.

Copy link
Contributor

@dcherian dcherian left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like an improvement; let's just add a whats-new note.

@Illviljan Illviljan added the plan to merge Final call for comments label Aug 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
plan to merge Final call for comments topic-plotting
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Logscale color normalization in contourf
2 participants