Han Zhengzu
Han Zhengzu

Reputation: 3852

pcolormesh with user-defined value level

When I use plt.pcolormesh(xx,cmap =xx), I can't set the minimum value for plotting.

For example, I draw a 2-D array data which presents the population density of some area.

If I want to show the population density which exceed to some value(like 4500 people/Km2), I can use plt.contourf(pop,levels = [4500,6000,xxxx,xxxxx]) to solve that.

But I want to use pcolormesh style, I have thought about two methods:

Upvotes: 0

Views: 7691

Answers (1)

Deditos
Deditos

Reputation: 1415

The two most obvious choices to me are (1) convert the data to a masked array and set the color using the set_bad() method of the colormap or (2) use the vmin argument to pcolormesh() and set the color using the set_under() method of the colormap.

Here's an example using some data in a Numpy array, xx, that have values between 0 and 57. I've masked values less than 25 and set the plot color to black for the masked values just so it's easier to see the effect.

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

F, (A1,A2) = plt.subplots(ncols=2,figsize=(15,5))

# Option 1:
xxm = np.ma.masked_less(x,25)

cmap1 = cm.get_cmap("jet",lut=10)
cmap1.set_bad("k")

A1.set_title("Using masked array")
P = A1.pcolormesh(LON,LAT,xxm,cmap=cmap1)
plt.colorbar(P,ax=A1)

# Option 2:
cmap2 = cm.get_cmap("jet",lut=10)
cmap2.set_under("k")

A2.set_title("Using vmin")
P = A2.pcolormesh(LON,LAT,xx,cmap=cmap2,vmin=25)
plt.colorbar(P,ax=A2)

plt.show()

enter image description here

Upvotes: 3

Related Questions