Display Matplotlib Plots in Pygame: A Step-by-Step Guide

Our tasks for this

Import necessary module



import sys
import pygame
import matplotlib
from pygame.locals import *
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas



from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas

This code imports a tool from Matplotlib that lets you save plots as image files (like PNG or JPG). Use this for embedding plots in websites, reports, or presentations. We will apply this to implement in pygame.

Initiate pygame and setup the display



pygame.init()

clock = pygame.time.Clock() 
display_screen = pygame.display.set_mode((1200, 600))
background_color = (144, 238, 144)


we will use pygame.time.Clock() to control the frame rate of this application

Create a Matplotlib figure and canvas



figure, axis = plt.subplots()
axis.plot([1, 2, 3, 4, 5, 6, 7], [10, 20, 25, 30, 25, 45, 50]) 
plot_canvas = FigureCanvas(figure)  # Create a canvas to render the Matplotlib plot 



  • figure, axis = plt.subplots()
    This sets up your plotting area. Imagine fig as a picture frame, and axis as the place inside it for our graph.

  • axis.plot([1, 2, 3, …], [10, 20, 25, …])
    This draws the line. The numbers are coordinates (like on a map) for the line’s points.

  • plot_canvas = FigureCanvas(figure)
    This line gets our plot ready to be turned into an image file if needed.”

Apply the drawing and update in the while loop



# Main game loop
running = True
while running:
    clock.tick(10)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    display_screen.fill(background_color)

    # Draw the Matplotlib plot onto the Pygame screen
    plot_canvas.draw()  # Update the Matplotlib plot if needed
    renderer = plot_canvas.get_renderer()  
    matplotlib_plot_rgba_image_data = renderer.tostring_rgb()  # Get raw image data of the plot
    plot_canvas_width, plot_canvas_height = plot_canvas.get_width_height() 

    # Convert the Matplotlib image data into a Pygame surface
    plot_surface = pygame.image.fromstring(matplotlib_plot_rgba_image_data, 
                                           (plot_canvas_width, plot_canvas_height), 
                                           "RGB")

    # Display the plot on the Pygame screen
    display_screen.blit(plot_surface, (300, 50))  # Place the plot at position (300, 50)

    pygame.display.update()


The complete Code



import sys
import pygame
import matplotlib
from pygame.locals import *
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas

# Initialize Pygame
pygame.init()

# Set up the display window
clock = pygame.time.Clock()  # Used to control the speed of the game loop
display_screen = pygame.display.set_mode((1200, 600))  # Create a window 1200 pixels wide, 600 pixels tall
background_color = (144, 238, 144)  # A light green color

# Create the Matplotlib plot 
figure, axis = plt.subplots()  # Create a figure (the container) and an axis (for plotting)
axis.plot([1, 2, 3, 4, 5, 6, 7], [10, 20, 25, 30, 25, 45, 50])  # Plot sample data 
plot_canvas = FigureCanvas(figure)  # Create a canvas to render the Matplotlib plot 

# Main game loop
running = True
while running:
    clock.tick(10)  # Limit the loop to run 10 times per second

    # Handle events (like keyboard presses, mouse clicks)
    for event in pygame.event.get():
        if event.type == QUIT:  # Check if the user clicked the close button
            pygame.quit()
            sys.exit()

    # Clear the screen with the background color
    display_screen.fill(background_color)

    # Draw the Matplotlib plot onto the Pygame screen
    plot_canvas.draw()  # Update the Matplotlib plot if needed
    renderer = plot_canvas.get_renderer()  
    matplotlib_plot_rgba_image_data = renderer.tostring_rgb()  # Get raw image data of the plot
    plot_canvas_width, plot_canvas_height = plot_canvas.get_width_height() 

    # Convert the Matplotlib image data into a Pygame surface
    plot_surface = pygame.image.fromstring(matplotlib_plot_rgba_image_data, 
                                           (plot_canvas_width, plot_canvas_height), 
                                           "RGB")

    # Display the plot on the Pygame screen
    display_screen.blit(plot_surface, (300, 50))  # Place the plot at position (300, 50)

    # Update the display to show changes
    pygame.display.update()




More Pygame related Article

https://programmerbee.com/category/pygame/

More pygame example codes on github

Related Posts

Create And Train Simple Artificial Neuron with python : Teach a Neuron to Sum two number
July 1, 2024

We will start this example with simplest neuron then train it to sum two number so it will be simple. And best part is for simplicity we will use only python standard library. We will write everything from scratch.. First the basics. Like our biological neuron artificial neuron can learn and change over time. Human […]

Converting Between Python Dictionaries and JSON
May 30, 2024

We will use json.dums() function to convert to json from python dictionary and json.loads() to convert from json to python dictionary. In this example code we used flower details data in python dictionary and converted it to json. import json # flowers in python dictionary flowers = { “rose”: { “scientific_name”: “Rosa”, “grows_in”: [“gardens”, “wild”], […]

How to create, read and write csv file from python
March 17, 2024

First Lets talk about csv Its a plain text format which comes from (Comma Separated Values) Most spreadsheet application supports this. You can open and edit it from excl, Libra office cal , google sheets and other spread sheet application, also supported by most of the programming language. For simplicity and flexibility often used in […]