简体   繁体   中英

Python matplotlib mask multiple (more than three) values using pcolormesh

I would like to use matplotlibs pcolormesh and mask data (ie indicate with a special color not part of the chosen colormap) for more than 3 types of data in the colormap. As this example shows, it is clear how to do that for three types by using the three functions:

cmap.set_under('yellow')
cmap.set_over('cyan')
cmap.set_bad('blue')

But how can one do this for values that are 'not bad', not under or over a given range, but just deserve special attention eg for indicating the 'best values' (which are within a given range) in the data displayed as colormap. In terms of code: the indices_to_be_masked_with_another_color below shall be colored differently (not using a color from the colormap).

import matplotlib.pyplot as plt
import numpy as np
import copy

np.random.seed(0)
D = np.random.rand(12, 72)
D[4, :] = np.nan
D[6, 6] = np.nan
D[2, :] = np.linspace(0.4, 0.6, D[2, :].size)
D = np.ma.masked_invalid(D)
cmap = copy.copy(plt.get_cmap('bwr'))
cmap.set_bad(color = 'k', alpha = 1.)
cmap.set_under(color = 'cyan')
cmap.set_over(color = 'yellow')
xbin = np.linspace(0, 12, 13)
ybin = np.linspace(-90, 90, 73)

fig = plt.figure()
ax = fig.add_subplot(111)
pl = ax.pcolormesh(xbin, ybin, D.T, cmap = cmap, edgecolors = 'None',
                vmin = 0.1, vmax = 0.9)

indices_to_be_masked_with_another_color = np.where(np.abs(D - 0.5) < 0.1)
# what to do now?

plt.show()

All values in the third column should have a special color, eg green

在此处输入图片说明

You can do it with these lines:

import matplotlib.colors as colors

ind = (np.abs(D.T - 0.5) > 0.1)
new_D = np.ma.masked_array(D.T,mask=ind)
greenmap = colors.ListedColormap(['g'])
ax.pcolormesh(xbin,ybin,new_D,cmap=greenmap,edgecolors='None')

在此处输入图片说明

First, you don't need to use np.where , but instead create a new mask for those values that you don't want to be green.

Then you create a listed colormap (of just green) to use with pcolormesh

Finally, you use this masked array and new colormap to plot another pcolormesh on top of your other one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM