Matplotlib ValueError on LogNorm plots

Matplotlib log10-normalized plots are enabled with the norm=LogNorm() option. However, vmin=0 in a log-norm pcolormesh() plot will cause

ValueError: Data has no positive values, and therefore can not be log-scaled.

Fix

The fix is entirely in the use of LOGMIN chosen appropriate for your data. This does NOT modify your original data values.


import numpy as np
from matplotlib.pyplot import subplots,show
from matplotlib.colors import LogNorm

LOGMIN = 0.1  # a priori chosen 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,ax = subplots(1,2,figsize=(12,5))
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')

show()

Matlab / Octave

The equivalent code in Matlab/GNU Octave does not give an error.

try
  pkg load statistics
end

dat = raylrnd(1.,[50,50]);

dat(1,1) = 0;  

figure()
subplot(1,2,1)
pcolor(log10(dat))  
title('log')

subplot(1,2,2)
pcolor(dat)
title('linear')

Leave a Comment