2

I'm trying to learn how to do a heatmap in Python using matplotlib. I'm going to be plotting a series of locations in a huge X,Y grid based off of an array of tuples. I found this code example which gives a perfect example of what I want to do. I can't seem to understand what the different parts of it mean though. Ultimately I want to output this on an overlay of an existing image. Thanks!

Community
  • 1
  • 1

1 Answers1

9

Nothing there is complicated. Anyway, here is a more simplified edition:

import pylab as pl
import numpy as np

n = 300                                     #number of sample data
x,y = np.random.rand(2,n)                   #generate random sample locations

pl.subplot(121)                             #sub-plot area 1 out of 2
pl.scatter(x,y,lw=0,c='k')                  #darw sample points
pl.axis('image')                            #necessary for correct aspect ratio

pl.subplot(122)                             #sub-plot area 2 out of 2

pl.hexbin(x,y,C=None,gridsize=15,bins=None,mincnt=1)        #hexbinning

pl.scatter(x,y,lw=0.5,c='k',edgecolor='w')  #overlaying the sample points
pl.axis('image')                            #necessary for correct aspect ratio

pl.show()                                   #to show the plot

Sample Points:
sample points

Hexbin result:
bexbin

Note that mincnt=1 avoids plotting hexagon for empty cells. A hexagon cell with dark red has more number of sample points (here 5) inside. Dark blue hexagons have only one sample inside.

Spencer Hill
  • 899
  • 6
  • 23
Developer
  • 8,258
  • 8
  • 49
  • 58
  • Since OP want it as a translucent overlay, I suggest adding one `imshow()` line and using the `alpha` keyword for `hexbin`. – Hannes Ovrén Dec 24 '13 at 09:21
  • I ended up finding a guide that goes into more detail here, http://scipy-lectures.github.io/intro/matplotlib/matplotlib.html#simple-plot – Alexandertyler Dec 24 '13 at 22:46
  • Also check out [this brief tutorial](https://github.com/Rblivingstone/datawrangling/blob/master/scatterplots.ipynb) – Ryan Apr 12 '17 at 22:00