简体   繁体   中英

Is there a cmap which goes from transparant to black (or any other color)?

I'm using the following cmap="binary" on a datasets with zeros and ones. The cmap goes from white to black. This results in the following figure:

Black and white figure:

Because I want to overlap this graph with an existing graph, I want to keep the black but make the white transparant.

Overlapping image with white:

Is there a cmap which goes from transparancy to black ?

I'm using the following code to plot the graphs:

plt.pcolor(mp1,cmap="binary",alpha=0.5)

It's not too difficult to define your own RGBA colour-maps ( source ). For example, to define a black colour map with linearly varying transparency:

from matplotlib.colors import ListedColormap

cmap = np.zeros([256, 4])
cmap[:, 3] = np.linspace(0, 1, 256)
cmap = ListedColormap(cmap)

Example usage:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

x = 2 * np.pi * np.linspace(-1, 1, 100)

z = np.sin(x.reshape(1, -1) + x.reshape(-1, 1))

cmap = np.zeros([256, 4])
cmap[:, 3] = np.linspace(0, 1, 256)
cmap = ListedColormap(cmap)

plt.figure()
plt.pcolormesh(z + 1, cmap='bwr', edgecolors=None)
plt.pcolormesh(np.fliplr(z), cmap=cmap, edgecolors=None)
plt.savefig("temp")

Output:

输出图像 temp.png

Found the solution!

            c_white = matplotlib.colors.colorConverter.to_rgba('white',alpha = 0)
            c_black= matplotlib.colors.colorConverter.to_rgba('black',alpha = 1)
            cmap_rb = matplotlib.colors.LinearSegmentedColormap.from_list('rb_cmap',[c_white,c_black],512)
            
            
            pl = plt.pcolor(mp1,cmap=cmap_rb)

If mp1 only has the values 0 and 1, and nothing inbetween, you can mask out the zeros and only plot the ones. np.where(mp1 == 1, 1, np.nan) will only show the ones. Using vmin=0 will make sure 0 maps to the white of the 'binary' colormap and vmax=1 will map 1 to black.

import matplotlib.pyplot as plt
import numpy as np

mp0 = np.random.randn(15, 30).cumsum(axis=1).cumsum(axis=0) # random backgroud
mp1 = np.zeros((15, 30)) # start with all zeros
mp1[np.random.randint(0, 15, 30), np.random.randint(0, 30, 30)] = 1 # set some random positions to 1

plt.pcolormesh(mp0, cmap='rainbow')
plt.pcolormesh(np.where(mp1 == 1, 1, np.nan), cmap='binary', vmin=0, vmax=1)

plt.tight_layout()
plt.show()

示例图

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