How to ignore NaN in colorbar?

I have a three-dimensional surface, followed by a color bar created

surf = ax.plot_surface(xv, yv, zv, ...) cb = fig.colorbar(surf) 

When it works, it looks like this:

enter image description here

The problem is that some of the values ​​may be NaN, in which case the color bar cannot be generated, for example:

Example

 C:\Users\Sam\Anaconda\lib\site-packages\matplotlib\colorbar.py:581: RuntimeWarning: invalid value encountered in greater inrange = (ticks > -0.001) & (ticks < 1.001) C:\Users\Sam\Anaconda\lib\site-packages\matplotlib\colorbar.py:581: RuntimeWarning: invalid value encountered in less inrange = (ticks > -0.001) & (ticks < 1.001) C:\Users\Sam\Anaconda\lib\site-packages\matplotlib\colors.py:576: RuntimeWarning: invalid value encountered in less cbook._putmask(xa, xa < 0.0, -1) 

I could try replacing NaN zv values ​​with 0 ( zv[isnan(zv)] = 0 ), but then the resulting graph has vertical cliffs that confuse and obscure some of the functions, and it distorts the color bar.

enter image description here

I want the color bar to ignore NaN values. To do this, I could manually set the color bar (before amin(zv[~isnan(zv)]) and amax(zv[~isnan(zv)]) ) after creating it, but I don’t know how to do it.

Any suggestions on how to ignore NaN when calculating a color panel and when painting a 3d surface?

+6
source share
2 answers

Set the vmin and vmax parameters when calling plot_surface . These values ​​affect the minimum and maximum values ​​displayed by the color bar.

 import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as axes3d def peaks(x, y): return x*np.sin(y) fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection='3d') X, Y = np.meshgrid(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100)) Z = peaks(X, Y) Z[X+Y>3] = np.nan surf = ax.plot_surface(X, Y, Z, alpha=0.3, cmap=plt.cm.jet, vmin=np.nanmin(Z), vmax=np.nanmax(Z)) cbar = plt.colorbar(surf) plt.show() 

enter image description here

+8
source

You should be able to exclude NaN from zv before surfing, for example:

 surf = ax.plot_surface(xv, yv, zv[~isnan(zv)], ...) cb = fig.colorbar(surf) 

This should completely solve the problem if I understand it correctly. Of course I can confuse. Good luck.

-1
source

All Articles