首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使set_under和set_bad同时工作在matplotlib等值线图中

使set_under和set_bad同时工作在matplotlib等值线图中
EN

Stack Overflow用户
提问于 2017-05-12 17:51:50
回答 2查看 4.2K关注 0票数 5

我试图生成一个matplotlib contourf图,它的所有值都在指定的白色值(包括零)下,而所有nan值(表示缺失的数据)都是黑色的。我似乎无法使nan值变成不同的颜色,而不是以下/零值。

代码语言:javascript
运行
复制
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

# Generate some random data for a contour plot
Z = np.random.rand(10,10)
Z[0:3,0:3] = np.nan # some bad values for set_bad
Z[0:3,7:10] = 0 # some zero values for set_under
x = np.arange(10)
y = np.arange(10)
X,Y = np.meshgrid(x, y)

# Mask the bad data:
Z_masked = np.ma.array(Z,mask=np.isnan(Z))

# Get the colormap and set the under and bad colors
colMap = cm.gist_rainbow
colMap.set_bad(color='black')
colMap.set_under(color='white')

# Create the contour plot
plt.figure(figsize=(10, 9))
contourPlot = plt.contourf(X,Y,Z_masked,cmap = colMap,vmin = 0.2)
plt.colorbar(contourPlot)
plt.show()

使用这种方法,我得到了下面链接的数字,其中nan值(左下角)和零值(右下角)都是白色的--我不知道为什么nan值不是黑色的。

生成图形

EN

Stack Overflow用户

回答已采纳

发布于 2017-05-12 18:23:07

关键是@ViníciusAguia所指出的示例,它指出contourf在数据无效时不会绘制任何内容。如果你在你的例子中翻转了黑白相间,它看起来就像起作用了!

得到你想要的东西的一种方法是把你的斧头上的面部颜色设置成你想要的‘坏’的颜色:

代码语言:javascript
运行
复制
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
plt.ion()

# Generate some random data for a contour plot
Z = np.random.rand(10,10)
Z[0:3,0:3] = np.nan # some bad values for set_bad
Z[0:3,7:10] = 0 # some zero values for set_under
x = np.arange(10)
y = np.arange(10)
X,Y = np.meshgrid(x, y)

# Mask the bad data:
Z_masked = np.ma.array(Z,mask=np.isnan(Z))

# Get the colormap and set the under and bad colors
colMap = cm.gist_rainbow
# this has no effect see last comment block in
# https://matplotlib.org/examples/pylab_examples/contourf_demo.html
# colMap.set_bad(color='black')
colMap.set_under(color='white')

# Create the contour plot
fig, ax = plt.subplots()
contourPlot = ax.contourf(X,Y,Z_masked,cmap = colMap,vmin = 0.2, extend='both')
fig.colorbar(contourPlot)
# This is effectively 'bad' for contourf
ax.set_facecolor('k')
plt.show()

票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43943784

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档