Matplotlib ValueError on LogNorm plots

less than 1 minute read

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. Even with Matplotlib 2.1.1, which

change default logscale behavior to clip

still gives ValueError without the LOGMIN fix below.

import numpy as np
from matplotlib.pyplot import figure,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  

ax = figure(figsize=(12,5)).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')

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