gpt4 book ai didi

python - 让 set_under 和 set_bad 在 matplotlib contourf plot 中工作

转载 作者:行者123 更新时间:2023-11-28 17:16:13 25 4
gpt4 key购买 nike

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

buggy figure

Generated Figure

最佳答案

由于屏蔽区域根本没有填充,您可以简单地将图的背景设置为您想要归因于“坏”值的颜色,plt.gca().set_facecolor("black ").

完整示例:

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_under(color='white')

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

enter image description here

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com