当不存在轮廓时,Matplotlib contourplot 失败

Matplotlib contourplot fails when no contour exists

我使用食谱示例 frin http://wiki.scipy.org/Cookbook/Matplotlib/Gridding_irregularly_spaced_data 来制作等高线图。然而,我的一些数据可能只包含零,在这种情况下,我得到一个 ValueError:zero 大小的数组,以减少操作最小值,它没有标识。

import numpy as np
from scipy.interpolate import griddata
import matplotlib.pyplot as plt
from numpy.random import uniform, seed


# make up some randomly distributed data
seed(1234)
npts = 200
x = uniform(-2,2,npts)
y = uniform(-2,2,npts)
z = 0*x*np.exp(-x**2-y**2) #Here i multiply by zero
# define grid.
xi = np.linspace(-2.1,2.1,100)
yi = np.linspace(-2.1,2.1,100)
# grid the data.
zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='cubic')

#zi[0][0]=0.00001 would make everything ok again
print(zi)
# do the plotting and save the result
CS = plt.contour(xi, yi, zi)
plt.show()

有没有优雅的方法来处理这个问题? 这个在matplotlib里值不值票?

为什么不直接捕获异常,即:

try:
    CS = plt.contour(xi, yi, zi)
    plt.show()
except ValueError:
    print("Can't plot this data")