我想要叠加几个hexbin图,但是使用内置颜色图只能看到最后一个。我不想重新构建色彩映射。如何在不事先知道色彩图的内部结构的情况下为色彩图添加线性alpha?
答案 0 :(得分:31)
答案 1 :(得分:3)
我想通过修正来扩展Bart的答案,从而消除颜色栏中的线条瑕疵。已有的历史:直到今天,这些线条伪影仍然存在,并且没有很好地解决(请参见Matplotlib: Add a custom colorbar that runs from full transparent to full color (remove artifacts),why does my colorbar have lines in it?)。但是,具有alpha通道的每种颜色都不过是该颜色与其背景的混合。因此,如果您知道背景,则可以计算相应的非alpha颜色(请参见https://www.viget.com/articles/equating-color-and-transparency/)。
以下解决方案假定,该图不需要实际的透明度。如果需要,请在图形中使用真实的Alpha,并根据需要使用自己的颜色图和计算出的非Alpha颜色值。
import numpy as np
import matplotlib.pylab as pl
from matplotlib.colors import ListedColormap
# Random data
data1 = np.random.random((4,4))
# Choose colormap which will be mixed with the alpha values
cmap = pl.cm.RdBu
# Get the colormap colors
my_cmap = cmap(np.arange(cmap.N))
# Define the alphas in the range from 0 to 1
alphas = np.linspace(0, 1, cmap.N)
# Define the background as white
BG = np.asarray([1., 1., 1.,])
# Mix the colors with the background
for i in range(cmap.N):
my_cmap[i,:-1] = my_cmap[i,:-1] * alphas[i] + BG * (1.-alphas[i])
# Create new colormap which mimics the alpha values
my_cmap = ListedColormap(my_cmap)
# Plot
f, axs = pl.subplots(1,2, figsize=(8,3))
h = axs[0].pcolormesh(data1, cmap=pl.cm.RdBu)
cb = f.colorbar(h, ax=axs[0])
h = axs[1].pcolormesh(data1, cmap=my_cmap)
cb = pl.colorbar(h, ax=axs[1])
f.show()