问题描述
我试图在 matplotlib 中使用 imshow 将数据绘制为热图,但其中一些值是 NaN.我希望将 NaN 呈现为颜色图中未找到的特殊颜色.
I am trying to use imshow in matplotlib to plot data as a heatmap, but some of the values are NaNs. I'd like the NaNs to be rendered as a special color not found in the colormap.
示例:
import numpy as np
import matplotlib.pyplot as plt
f = plt.figure()
ax = f.add_subplot(111)
a = np.arange(25).reshape((5,5)).astype(float)
a[3,:] = np.nan
ax.imshow(a, interpolation='nearest')
f.canvas.draw()
结果图像出乎意料地全是蓝色(jet 颜色图中的最低颜色).但是,如果我这样绘制:
The resultant image is unexpectedly all blue (the lowest color in the jet colormap). However, if I do the plotting like this:
ax.imshow(a, interpolation='nearest', vmin=0, vmax=24)
--然后我得到了更好的东西,但是 NaN 值绘制的颜色与 vmin 相同...有没有一种优雅的方法可以将 NaN 设置为使用特殊颜色(例如:灰色或透明)绘制?
--then I get something better, but the NaN values are drawn the same color as vmin... Is there a graceful way that I can set NaNs to be drawn with a special color (eg: gray or transparent)?
推荐答案
使用较新版本的 Matplotlib,不再需要使用掩码数组.
With newer versions of Matplotlib, it is not necessary to use a masked array anymore.
例如,让我们生成一个数组,其中每 7 个值都是一个 NaN:
For example, let’s generate an array where every 7th value is a NaN:
arr = np.arange(100, dtype=float).reshape(10, 10)
arr[~(arr % 7).astype(bool)] = np.nan
我们可以修改当前的颜色图并使用以下几行绘制数组:
We can modify the current colormap and plot the array with the following lines:
current_cmap = matplotlib.cm.get_cmap()
current_cmap.set_bad(color='red')
plt.imshow(arr)
这篇关于如何在 matplotlib 中使用 imshow 将 NaN 值绘制为特殊颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!