Jerome
Jerome

Reputation: 49

How to plot heatmap from standard deviation of binned data?

I am trying to make a heatmap of standard deviations (stdv) from gridded data, i.e. data which I have divided up into cells like a grid and I want to obtain stdv from each of those cells and plot its value as in each cell, colour-coded as a heatmap. Below is the code i used to divide the x -y plane into 4 equal bins or cells ad then let v-values fall into those 4 bins. I print them out and their respective stdv in each bin.

import numpy as np
import matplotlib.pyplot as plt
x = np.array([-10,-2,4,12,3,6,8,14,3])
y = np.array([5,5,-6,8,-20,10,2,2,8])
v = np.array([4,-6,-10,40,22,-14,20,8,-10])

xi = x // 20+1

yi = y // 20+1

k=2
cells = [[[] for yi in range(k)] for xi in range(k)]

for ycell in range(k):
    for xcell in range(k):
        cells[ycell][xcell] = v[(yi == xcell) & (xi == ycell)]
       
for ycell in range(k):
    for xcell in range(k):
        this = cells[ycell][xcell]
        print(ycell, xcell, len(this), this, sep='\t')
        print('direct std dev is', np.std(this))

I now want to plot this on the x-y plane with each of those 4 bins representing stdv value as intensity and appear as a heatmap like the following figure :

enter image description here

Could someone please help me figure out how to create this sort of heatmap? Thanks!

Upvotes: 0

Views: 1009

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150785

Do you mean:

k=2
cells = [[[] for yi in range(k)] for xi in range(k)]
stds = [[[] for yi in range(k)] for xi in range(k)]

for ycell in range(k):
    for xcell in range(k):
        cells[ycell][xcell] = v[(yi == xcell) & (xi == ycell)]

        # replace invalid (np.nan) with 0
        stds[ycell][xcell] = np.std(cells[ycell][xcell]) or 0

# import plot lib
import seaborn as sns

# heatmap
sns.heatmap(stds, cmap='Blues', annot=True)

Output:

enter image description here

Upvotes: 1

Related Questions