我正在尝试生成一个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值不为黑色。

python - 使set_under和set_bad都在matplotlib Contourf图中工作-LMLPHP

Generated Figure

最佳答案

关键是@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()

python - 使set_under和set_bad都在matplotlib Contourf图中工作-LMLPHP

关于python - 使set_under和set_bad都在matplotlib Contourf图中工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43943784/

10-12 23:59