Graphical displays with Python and Pygame


graphLine takes four arguments, a list of data to graph, a corresponding list of labels for each data point, and the start and end index to graph. First, all of the graphing locations are calculated relative to the screen size (lines 43 and 44). Next, the internal function walkValues returns evenly spaced values across the entire list. For each value returned, it checks whether the value is lower or higher than the extents seen so far and updates the min and max values if necessary. Then, it appends the value to the internal list of points to graph (lines 45-49).

walkValues is a Python generator, similar to range. In fact, it uses range to get the values once it's calculated the appropriate space between each element. By using yield (lines 72, 73) it becomes a generator that can feed a for loop directly.

When you call a generator, it actually returns a Python object. Each call to the object returns the next calculated value, indicated by yield, then execution stops. The process repeats on each call to the object. When the last value has been yielded, the generator is considered empty.

walkValues accepts a start and end index, and the number of values to return within that range. This function returns the equally spaced values. After the loop, the last item is yielded, so the range always includes the start and end values provided at the initial call. The loop in lines 55-59 creates the line coordinates graphed on the screen and the label for each data point. Line 58 uses the transform module to rotate the label 45 degrees. rotate returns a surface padded to the appropriate size to accommodate the rotation. The label is blitted to the screen each time through the loop. Line 60 uses pygame.draw.lines to draw the line graph.


setupGraph calls all of the functions that don't rely on the scale of the data. The axes, hashes, and grid are spaced on the basis of hard-coded values that could be converted to a class variable for more flexibility.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Raspberry Pi Geek

Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content