如何使用 imshow 将 NaN 值绘制为特殊颜色?
我试图在 matplotlib 中使用 imshow 将数据绘制为热图,但某些值是 NaN。我希望将 NaN 渲染为颜色图中未找到的特殊颜色。
示例:
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 颜色图中最低的颜色)。但是,如果我像这样进行绘图:
ax.imshow(a, interpolation='nearest', vmin=0, vmax=24)
--然后我会得到更好的东西,但是 NaN 值绘制为与 vmin 相同的颜色...是否有一种优雅的方法可以将 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.
example:
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)
--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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯,看来我可以使用屏蔽数组来做到这一点:
这应该足够了,尽管我仍然愿意接受建议。 :]
Hrm, it appears I can use a masked array to do this:
This should suffice, though I'm still open to suggestions. :]
使用较新版本的 Matplotlib,不再需要使用屏蔽数组。
例如,让我们生成一个数组,其中每个第 7 个值都是 NaN:
.cm.get_cmap()
在matplotlib v3.7.0
中被替换为.colormaps.get_cmap('viridis')
设置颜色为
.set_bad
。.cm.get_cmap()
已弃用我们可以修改当前颜色图并绘制包含以下行的数组:
With newer versions of Matplotlib, it is not necessary to use a masked array anymore.
For example, let’s generate an array where every 7th value is a NaN:
.cm.get_cmap()
is replaced by.colormaps.get_cmap('viridis')
inmatplotlib v3.7.0
Set the color with
.set_bad
..cm.get_cmap()
is deprecatedWe can modify the current colormap and plot the array with the following lines: