Matplotlib ValueError on LogNorm plots
Matplotlib log10-normalized plots are enabled with plotting options
pcolormesh(dat, norm=matplotlib.colors.LogNorm(), vmin=max(dat.min(), LOGMIN))
This option also works for appropriate 2-D plots from
pandas.DataFrame.plot()
and xarray.DataArray.plot()
.
Log(0) bounds error
Explicit plot option vmin=0
or implicit (from data with a minimum of zero) in a log-norm pcolormesh()
plot will cause errors like
ValueError: Data has no positive values, and therefore can not be log-scaled.
or
ZeroDivisionError: float division by zero
Fix
Choose a minimum plot value LOGMIN
appropriate for plotting the data.
import numpy as np
from matplotlib.figure import Figure
from matplotlib.colors import LogNorm
LOGMIN = 0.1 # arbitrary lower bound, as appropriate for log-scaled data display
dat = np.random.rayleigh(1., (50,50))
dat[0,0] = 0. # forcing the ValueError to occur with LogNorm
fg = Figure(figsize=(12,5))
ax = fg.subplots(1,2)
ax[0].pcolormesh(dat, norm=LogNorm(), vmin=max(dat.min(), LOGMIN))
# vmin= : this averts ValueError by having non-zero cdata minimum.
ax[0].set_title('log')
ax[1].pcolormesh(dat)
ax[1].set_title('linear')
fg.savefig("fig.png")
Matlab / GNU Octave
The equivalent code in Matlab / GNU Octave does not give an error.
dat = raylrnd(1., [50,50]);
dat(1,1) = 0;
pcolor(log10(dat))