Heatmap

A simple way is to store heat map as a numpy array and plot the array as an image

import numpy as np

import matplotlib.pyplot as plt

array = np.array([[1,2],[3,4]])

fig, ax = plt.subplots()

im = ax.imshow(array) // to plot a gray map, use:  im = ax.imshow(weights, cmap='gray') 

plt.show()


Heatmap of a matrix array with a color bar.

Note that the heatmap origin is the bottom left, which corresponds to the matrix's top left cell

So it looks like the matrix is fliped onto the heatmap, upside down...


import matplotlib.pyplot as plt

fig= plt.figure(figsize=(8,6))

heatmap = [

    [1,1]

    ,[10,10]

    ]

img = plt.imshow(

    heatmap,

    interpolation="nearest",

    origin="lower",

    aspect="auto",

    cmap='bwr',

    vmin=0,

    vmax=10,

)

plt.colorbar()

plt.show()


ANother way:

import pyodbc

import numpy as np

import matplotlib.pyplot as plt

fcnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=127.0.0.1;DATABASE=MyDB;Trusted_Connection=yes;')

cursor = cnxn.cursor()

cursor.execute("""SELECT  Age, SES, count(*) AS Count

            FROM [Test_VW]""")

rows = cursor.fetchall()

rows_array = np.array(rows)

X = rows_array[:, 0:1].astype(int) #Age 1st column

Y = rows_array[:, 1:2].astype(int) #SES 2nd column

W = rows_array[:, 2:3].astype(int) #Count 3rd column

X = np.reshape(X, (1, len(X)))[0] #convert to a row vector

Y = np.reshape(Y, (1, len(Y)))[0] #convert to a row vector

W = np.reshape(W, (1, len(W)))[0] #convert to a row vector

heatmap, xedges, yedges= np.histogram2d(Y, X, bins=[range(0,12),range(15,100,5)], weights=W)

plt.imshow(heatmap, interpolation='none', origin='lower'

plt.colorbar()

The default histogram2d coordinate system is as following, so swap X, Y to Y, X to assign X to the horizontal axis

 ---------------------->Y

 |

 |

 |

 |

 |

 |

 |

 |X

The bins = [] specifies the boundaries of the bins in X and Y axes. Alternatively one can specify the number of bins and the function will divide it automatically.

In the imshow function, the origin ='lower/upper' so the (0,0) locates at the bottom left instead of top left.

The interpolation='none' cancels interpolation so each bin of the heatmap is a square instead of being smoothed.

The X and Y labels are the number of bins so they are not the actual value of X / Y, still need to figure out how to set the label????