How to output color to transparent using hexbin and matplotlib?

I am creating a "Heatmap" using hexbin and I want this heatmap to be placed on top of the image. However, I would like the graph coloring to fade out to transparency, like a frequency (i.e. when a color fades to white it fades out). I tried changing the alpha value, but that doesn't give the desired effect.

My code:

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') 

      

I am open to using 2d histogram or any other plotting function. Even just being transparent when there are no values ​​in that hex would be great, since many of my areas have data nulls.

Image of my current code:

Heatmap image

+3


source to share


1 answer


Rough example:

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') 

      



enter image description here

(I'm afraid my soccer field is sideways. I usually play as if it were.)

+2


source







All Articles