简体   繁体   中英

Matplotlib + Cartopy: How to use contourf with custom colormap

I have a set of points I'm using to plot a map using contourf .

I need to have a specific color pallet for this map, regarding specific data points, and a color to be set on data over the limit.

So, I have levels=[0, 2, 20, 100] and I'm looking for to have a cmap like the following one:

cmap=LinearSegmentedColormap.from_list([
  (0,   color1),
  (2,   color2),
  (20,  color3),
  (100, color4),
])
cmap.set_over(color5)

Problem is that the points must be normalized, like so:

cmap=LinearSegmentedColormap.from_list([
  (0 / max_value,   color1),
  (2 / max_value,   color2),
  (20 / max_value,  color3),
  (100 / max_value, color4),
])
cmap.set_over(color5)

My problem is, my data is variable, so I don't know what my max_value will be. I just want to "ignore" that the data is over 100, and paint it with color5 .

I know I can manipulate my data beforehand and make everything over 100 to actually BE 100, or to find the max_value in realtime, but those methods seem hackish to me.

Is there a way to accomplish that using matplotlib functions?

I ended up normalising my data, between [0,1] , like that:

def normalizer(lower_bound, upper_bound):
    _lower = float(lower_bound)
    _upper = float(upper_bound)

    def do_norm(x):
        return (float(x) - _lower) / (_upper - _lower)

    return do_norm

normalize = normalizer(0, 20)
normalize(10)  # 0.5

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