问题描述
我正在尝试在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()
生成的图像出乎意料地全是蓝色(喷射彩色图中的最低颜色).但是,如果我这样绘制:
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值绘制为特殊颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!