August 11, 2019

Improved Heatmap in Python



In addition to a previous posting an improved version of the heatmap sourcecode is given. The sourcecode was formatted in the HTML mode with the "pre" tag.

import pygame

class Game:
  def __init__(self):
    self.pygamewindow = pygame.display.set_mode((700, 350), pygame.HWSURFACE | pygame.DOUBLEBUF)    
    self.fps=5 # 20 
    for i in range(1000000):
      self.pygamewindow.fill(pygame.Color(255,255,255))   
      self.paintmap()
      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 baseid in range(len(gradient)):
      diff=value-gradient[baseid][0]
      if diff>=0 and diff<0.25: 
        break
    # relative color
    relvalue=(value-gradient[baseid][0])*1/0.25
    color=[] # (r,g,b)
    for i in range(1,4):
      temp=(gradient[baseid+1][i]-gradient[baseid][i])*relvalue # get difference
      temp=(temp+gradient[baseid][i])*255 # convert to 255 scale
      temp=int(round(temp)) # round
      color.append(temp)
    return color  
  def paintmap(self):
    width=pygame.display.get_surface().get_width()
    grid_width,grid_height=20,300
    maxstep=int(round(width/grid_width))
    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,0,grid_width,grid_height))

mygame=Game()
The advantage is, that the resolution can be adjusted easily to reduce the gridwidth.

No comments:

Post a Comment