matplotlib 在使用Cartopy时,如何让pcolor以白色绘制NaN值?

hs1rzwqc  于 2023-03-09  发布在  其他
关注(0)|答案(2)|浏览(223)

我在python中使用Cartopy和pcolor在海洋Map上绘制一些整数值标签。我希望NaN值显示为白色补丁。然而,目前NaN值是使用颜色图中最低的颜色绘制的。我如何让pcolor以白色显示NaN值?
Here is an example map where pcolor displays NaN values using a color, instead of white
我试过使用cmap.set_bad这样的函数来调整色彩Map表,但到目前为止我还不能让它工作。我也试过使用掩码数组,但它也不起作用。我在下面包含了一些自包含的示例代码,它们至少在我的环境中重现了这个问题。

  1. import numpy as np
  2. import matplotlib as mpl
  3. import cartopy.crs as ccrs
  4. import cartopy.feature as cfeature
  5. import matplotlib.pyplot as plt
  6. from random import seed
  7. from random import randint
  8. ## set maximum number of integer labels
  9. n_comp = 4
  10. # generate random integer "labels" as example data
  11. seed(1)
  12. labels = np.zeros((128*64,1))
  13. for ncomp in range(0, 64*128-1):
  14. labels[ncomp] = randint(0, n_comp)
  15. # make array 2D for plotting
  16. labels2D = labels.reshape((128,64))
  17. # replace zero with nan
  18. labels2D[labels2D==0] = np.nan
  19. # create latitude / longitude data
  20. x = np.arange(0.0,360.0,2.815)
  21. xx = np.tile(x,[64,1])
  22. xx = xx.transpose()
  23. y = np.arange(-90,90,2.815)
  24. yy = np.tile(y,[128,1])
  25. # create figure and axes
  26. fig = plt.figure(figsize=(10, 5))
  27. ax = fig.add_subplot(1, 1, 1,
  28. projection=ccrs.Robinson(central_longitude=-150))
  29. # create colormap
  30. cmap=plt.get_cmap('Accent', n_comp+1)
  31. # use white color to mark 'bad' values
  32. cmap.set_bad(color='w')
  33. # use norm to define colormap
  34. boundaries = np.arange(0.5,n_comp+1,1)
  35. norm = mpl.colors.BoundaryNorm(boundaries, cmap.N, clip=True)
  36. # use pcolor to make label map
  37. labelMap = ax.pcolor(xx, yy, labels2D,
  38. transform=ccrs.PlateCarree(),
  39. norm=norm,
  40. cmap=cmap,
  41. vmin = 1,
  42. vmax = n_comp)
  43. # add continents on top of label data
  44. ax.add_feature(cfeature.LAND, zorder=1, edgecolor='black')
  45. # plot colorbar with ticks at centres of bars
  46. plt.colorbar(labelMap, ticks=np.arange(1,n_comp+1,1))
  47. # show plot
  48. plt.show()

我想用白色来表示NaN值,但目前它们是用颜色Map表中的颜色来绘制的。感谢您的帮助/指导。

qkf9rpyu

qkf9rpyu1#

你的代码对我有用,我得到白色值而不是颜色。
我使用的是麻醉1.15.0、MPL 2.2.2和心血管造影0.16.0
在苹果电脑上。

v1uwarro

v1uwarro2#

cmap.set_bad(color='w')也为我工作,当做:

  1. pcolormesh(data, norm=colors.LogNorm(vmin=vmin, vmax=vmax))

但在使用norm=colors.SymLogNorm()时不起作用

相关问题