# Pretty Plots with Pygame and Python

The other day I learned a little about the pygame python module that provides access to sdl functions on Linux along with some higher level functions. Basically, this means that you can use pygame to access some pretty low level graphics to draw things. I thought it might be fun to use it to make pretty pictures. Here’s an example where points are plotted, with the colour of each point a function of the coordinates. These simple examples should indicate how this type of low-level drawing can be used, perhaps to visualise complicated data or make interesting animations.

In sdl as with many computer graphics systems, coordinates start from the top left with $(0,0)$, and proceed positively right and down. The equations presented below give the red-green-blue (RGB) values of the color of the point at $(x,y)$. Each value is taken modulo $255$ (actually, I should have taken the value modulo $256$, since each color goes from $0$ to $255$, but I didn’t think carefully about this when I wrote the program!). \begin{align*} r &= x\\ g &= x-y\\ b &= x + y \end{align*} \begin{align*} r &= x^2\\ g &= x\\ b &= x+y \end{align*} \begin{align*} r &= 255*\cos(x)\\ g &= 255*\sin(x)\\ b &= xy \end{align*} \begin{align*} r &= 100 + y\\ g &= x/(10 + y)\\ b &= x – y^2 \end{align*} \begin{align*} r &= x + y + xy\\ g &= x – y + 240\\ b &= x + y^4 \end{align*} \begin{align*} r &= x^2\\ g &= 4y – x^4\\ b &= y^3 – y^2 + y \end{align*} \begin{align*} r &= xy\\ g &= x^5-y^5\\ b &= x^{13} \end{align*} \begin{align*} r &= x^2y^3\\ g &= y + x^2 + 7xy\\ b &= x + y^2 + x^3 + x^4 + y^6 \end{align*} \begin{align*} r &= 50*\sin(x^2 + y^2)\\ g &= 40 + 10\sin(x) + 20\cos(y)\\ b &= 200 \end{align*} \begin{align*} r &= (1 + x + 100x^3)/(1 + 25y^2)\\ g &= y/4\\ b &= (1 + 200y^3)/(1 + x^4) \end{align*}

Here is the code (since it’s so short, consider it public domain):

import sys,pygame
import random
import math
pygame.init()

sqsize = 400
size = width, height = sqsize,sqsize
black = 0,0,0
pos_x = 0
pos_y = 0

def draw_pixel(s, color, pos):
pygame.draw.line(s,color,pos,pos,1)

screen  = pygame.display.set_mode(size)
screen.fill(black)
done = False

while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
cred =  pos_x**2 - pos_y**2
cgreen = 123
cblue = 123
newcol = int(cred)%256, int(cgreen)%256,int(cblue)%256
if (not done) : draw_pixel(screen,newcol, (pos_x,pos_y))

if (pos_x < sqsize) : pos_x = pos_x + 1
else : pos_x = 0; pos_y = (pos_y + 1)%sqsize
if (pos_y==sqsize) : done=True
if (pos_x%120==0) : pygame.display.flip()