我试图生成一个matplotlib contourf图,它的所有值都在指定的白色值(包括零)下,而所有nan值(表示缺失的数据)都是黑色的。我似乎无法使nan值变成不同的颜色,而不是以下/零值。
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值不是黑色的。
发布于 2017-05-12 18:23:07
关键是@ViníciusAguia所指出的示例,它指出contourf在数据无效时不会绘制任何内容。如果你在你的例子中翻转了黑白相间,它看起来就像起作用了!
得到你想要的东西的一种方法是把你的斧头上的面部颜色设置成你想要的‘坏’的颜色:
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()
https://stackoverflow.com/questions/43943784
复制相似问题