August 10, 2019

Heatmap in Python



According to the website http://www.andrewnoske.com/wiki/Code_-_heatmaps_and_color_gradients a heatmap is created by a color gradient which goes from blue to cyan then to green, over yellow to red. For realizing a function which takes as input a value between 0 .. 1 and returns as output the colorcode the inbetween values of two categories needs to be calculated. The Python function for doing so is a bit longer and takes 25 lines of code. In the referenced URL only the C++ version was given, I have reprogrammed the code.
During the creation of the sourcecode, a slider widget from TKinter was a great help. This allows the user to set a value between 0 and 1 interactively and observe what the return value of the function is.

Update: Sometthing is wrong with the embedded sourcecode. It seems, that the if statement (font) was formatted by the Blog engine a bit randomly.

import pygame

class Game:
  def __init__(self):
    self.pygamewindow = pygame.display.set_mode((500, 350), pygame.HWSURFACE | pygame.DOUBLEBUF)    
    self.fps=20 # 20 
    for i in range(1000000):
      self.pygamewindow.fill(pygame.Color(255,255,255))   
      self.paintheatmap()
      pygame.display.update()
      pygame.time.wait(int(1000/self.fps))
  def heatmapcolor(self,value):
    # # value 0..1, returns colorcode (r,g,b) 
    # init gradient
    gradient=[]  # (value,r,g,b)
    gradient.append((0.0,  0,0,1)) # blue
    gradient.append((0.25, 0,1,1)) # cyan
    gradient.append((0.5,  0,1,0)) # green
    gradient.append((0.75, 1,1,0)) # yellow
    gradient.append((1.0,  1,0,0)) # red
    gradient.append((1.0,  1,0,0)) # red extra
    # search base color
    for i in range(len(gradient)):
      diff=value-gradient[i][0]
      if diff>=0 and diff<0 .25:="" font="" nbsp="">
        break
    # relative color
    relvalue=(value-gradient[i][0])*1/0.25
    red=(gradient[i+1][1]-gradient[i][1])*relvalue
    red=(red+gradient[i][1])*255
    green=(gradient[i+1][2]-gradient[i][2])*relvalue
    green=(green+gradient[i][2])*255
    blue=(gradient[i+1][3]-gradient[i][3])*relvalue
    blue=(blue+gradient[i][3])*255
    # result
    result=(int(round(red)),int(round(green)),int(round(blue)))
    return result      
  def paintheatmap(self):
    grid_width,grid_height=12,50
    maxstep=40
    for i in range(maxstep):
      value=i/maxstep # 0..1
      temp=self.heatmapcolor(value)
      col=pygame.Color(temp[0],temp[1],temp[2])
      x=0+i*grid_width
      pygame.draw.rect(self.pygamewindow, col, (x,3,grid_width,grid_height))

mygame=Game()