如何使用hexbin和matplotlib将颜色淡化为透明?

我正在使用hexbin创建一个“热图”,并希望将此热图放在图像的顶部.但是,我希望情节的着色随着频率的变化而变淡(即,当颜色渐变为白色时,它会消失).我已经尝试更改alpha值,但这不会产生预期的效果.

我的代码是:

n = 100000
x = np.random.standard_normal(n)
img = imread("soccer.jpg")
y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n)
plt.hexbin(x,y, bins='log', cmap=plt.cm.Reds, alpha = 0.3)
plt.imshow(img,zorder=0, extent=[-10, 10, -20, 20])
#plt.show()
plt.savefig('map.png') 

我愿意使用二维直方图或任何其他绘图功能.即使只是在六角形中没有值时透明也会很好,因为我的许多区域都没有数据点.

我当前代码生成的图像是:

《如何使用hexbin和matplotlib将颜色淡化为透明?》

最佳答案 正在进行的粗略示例:

n = 100000
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap


x = np.random.standard_normal(n)
img = plt.imread("soccer.jpg")
y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n)

red_high = ((0., 0., 0.),
         (.3, .5, 0.5),
         (1., 1., 1.))

blue_middle = ((0., .2, .2),
         (.3, .5, .5),
         (.8, .2, .2),
         (1., .1, .1))

green_none = ((0,0,0),(1,0,0))

cdict3 = {'red':  red_high,

     'green': green_none,

     'blue': blue_middle,

     'alpha': ((0.0, 0.0, 0.0),
               (0.3, 0.5, 0.5),
               (1.0, 1.0, 1.0))
    }


dropout_high = LinearSegmentedColormap('Dropout', cdict3)
plt.register_cmap(cmap = dropout_high)

plt.hexbin(x,y, bins='log', cmap=dropout_high)
plt.imshow(img,zorder=0, extent=[-10, 10, -20, 20])
plt.show()
#plt.savefig('map.png') 

《如何使用hexbin和matplotlib将颜色淡化为透明?》

(我担心我的足球场是侧身的.我通常会玩,就像它一样.)

点赞