Combining two matplotlib color maps

I would like to combine two colormaps into one so that I can use one cmapfor negative values ​​and the other for positive values.

At the moment I am doing this with masked arrays and drawing one image with one cmapand another image with another, resulting in:

enter image description here

with the following data

dat = np.random.rand(10,10) * 2 - 1
pos = np.ma.masked_array(dat, dat<0)
neg = np.ma.masked_array(dat, dat>=0)

I built poswith gist_heat_rand negwith help binary.

I would like to have one color bar with combined ones cmap, so for me this is not the right approach.

So, how do I take two existing ones cmapsand combine them into one?

EDIT: I admit this is a duplicate, but the answer that is given here is clearer. Also, sample images make this clearer.

+3
1

Colormaps - , . [0,1] . , , :

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

data = np.random.rand(10,10) * 2 - 1

# sample the colormaps that you want to use. Use 128 from each so we get 256
# colors in total
colors1 = plt.cm.binary(np.linspace(0., 1, 128))
colors2 = plt.cm.gist_heat_r(np.linspace(0, 1, 128))

# combine them and build a new colormap
colors = np.vstack((colors1, colors2))
mymap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors)

plt.pcolor(data, cmap=mymap)
plt.colorbar()
plt.show()

: enter image description here

. , , , , : -0,1 0,9? -0,9 0,1≤

- ~ 0.2 ~ 0.8 (: colors1 = plt.cm.binary(np.linspace(0.2, 0.8, 128))), :

enter image description here

+8

Source: https://habr.com/ru/post/1618679/


All Articles