Skip to main content

Interactive Plotting with Python and Matplotlib

Hello my friends, in this new entry I am going to show you how to make cool animations with some algebra and Python, algebra? Yes my friend, because animating an object is based on some transformation of coordinates, translating or rotating for example,  but we will get into that don't worry; Now let's talk about the Python Tools that we are going to use.
·         Numpy
·         Matplotlib
With numpy we can make and manipulate arrays with Python, the  array type in this package has methods that can use for common operations in algebra, among other uses with also are going to take into account the trigonometric functions, sin and cos, useful for rotations.
With matplotlib we can create pretty cool plots, and turning the interactive mode on, we can make some iteractive plots hence a cool animation. Let me show you the final result for our code so you can have a pretty good idea.




Cool right, as we can see on the animation, a small pacman figure is moving through a small maze, and in each corner it will turn or rotate to keep moving through the maze or blue path. The  code for this is very simple, so let's do the next thing, I will show you the entire code and explain the parts that could be tricky.
import numpy as np
import matplotlib.pyplot as plt
Functions

translate = lambda dx, dynp.matrix ([[10, dx], [01dy], [001]])

def rotate(angle):

    radians = angle * (np.pi / 180.0)

    return np.array([[np.cos(radians), -np.sin(radians), 0],
                      [np.sin(radians), np.cos(radians), 0],
                      [001]])

vector = lambda x: np.transpose(np.array(x))
   
def animate():

    '''
    Animation Function
    '''

    global dx, dyxcoordsycoordspacman_centercurrent_pacmanplt
   
    current_pacman = translate(dx, dy* current_pacman
    xcoords = np.array(current_pacman[0]).reshape(9)
    ycoords = np.array(current_pacman[1]).reshape(9)
    pacman_center[0+= dx
    pacman_center[1+= dy

    if pacman_center == [22.52.5]:
           
        dx = 0
        dy = 0.5
        current_pacman = translate(22.52.5* rotate(90* translate(-22.5-2.5* current_pacman

    elif pacman_center == [22.522.5]:

        dx = -0.5
        dy = 0
        current_pacman = translate(22.522.5* rotate(90* translate(-22.5-22.5* current_pacman
   
    elif pacman_center == [2.522.5]:

        dx = 0
        dy = -0.5
        current_pacman = translate(2.522.5* rotate(90* translate(-2.5-22.5* current_pacman

    elif pacman_center == [2.512.5]:

        dx = 0.5
        dy = 0
        current_pacman = translate(2.512.5* rotate(90* translate(-2.5-12.5* current_pacman

    elif pacman_center == [1412.5]:

        dx = 0
        dy = 0

    plt.fill(x_mazey_maze, color='b')
    plt.fill(xcoordsycoords, color='y')
    plt.plot(1412.5marker='d')
    plt.plot(22.52.5marker='*')
    plt.plot(22.522.5marker='*')
    plt.plot(2.522.5marker='*')
    plt.plot(2.512.5marker='*')
   
    return dx, dy
   

x_maze = np.array([0.025250015155520200])
y_maze = np.array([0.00252510101515202055])

xcoords = np.array([0.012323210])
ycoords = np.array([21122.53443])

zcoords = np.ones(len(xcoords))

pacman = np.array([xcoordsycoordszcoords])

plt.ion()
plt.axis('equal')
plt.axis([-530-530])

current_pacman = pacman

dx = 0.5
dy = 0.0
pacman_center = [1.52.5]

for i in range(200):

    if animate() == (00):
        break
   
    plt.pause(0.05)

As always we make the importation of the packages (our tools) that we are going to use, in this case numpy and matplotlib.
Then we are going to create some functions, 2 of those are anonymous functions, if you are not familiar with these kind of functions you can check my entry of lambda, these functions can take some arguments and will return a matrix or double size array, based on these matrix, by making dot product with some coordinates in array shape, you can rotate or translate those coordinates, in this way how we can make animations.
The main two steps in the animations are,
·         Create new coordinates, by translating or rotating
·         Update interactively the plot with new coordinates
These two steps are made in a function call animate, that takes the global variables with the coordinates of the maze and the packman figure and update the plot, in this functions there are also some conditional statements to check whether the pacman figure has reached a corner in order to rotate it.
Something else to point out is for us to be able to update the plot we need to turn the interactive mode of matplotlib on, we can do this by using plt.ion(), and that is all.
Finally we use a for loop for making the frame update with a pause to control the speed of refreshing the plot, and a conditional statement to break the for loop if the pacman figure has reached the end.
Well my friend we have come to the end of this entry, hope you can use some of this code in your programing.
 So thanks for coming by my new entry and I hope you have enjoyed this as much as I enjoyed writing it, stop by the comments if you want to discuss about this, share in your social media and subscribe. Cheers my friends.

Popular posts from this blog

Multithreading web scraping with Python

Hello my friends today in this entry we are going to talk about a very trendy topic, web scraping and how to do it with our beautiful Python programming language, so open your Python Idle and get set because in this Tutorial Entry we are going to code once again.

Python Free Books

Hello my friends in an earlier post I talked about some dive deep Python Books that you could purchase to start learning Python, you can check that entry in this link, and now I have decided to write this entry to give you a list of online and free Python books.


These books are supposed to be hosted documentation; they are written in restructured text (reStructuredText) and translated into beautiful HTML or PDF with a tool called Sphinx. This documentation format is supposed to be used for writing your own packages and modules documentation, but experts also use them to write practical books and tutorials of different languages and they can be uploaded and hosted for free in different online platforms, one of them is read the docs website.

Singleton - Design Patterns in Python

Hello my friends, here in this quickly entry we are going to talk about the most basic but very useful Design Pattern and that is the Singleton, but first let's discuss as always a little about theory.
Design PatternsThis is the next step in the programing learning curve, after Object Oriented Programming there is a list of topics that you could learn next, I strongly recommend Python Design Patterns. Accordingly to the Wikipedia, “a software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design”, in other words is the same code to the same kind of problems; in general we tend to find the same kind of problems when we are designing our software, and we tend to solve this problems with the same solution, in time and each time this solution is improved and finally is considered a standard or a pattern in software design, so it becomes a design pattern.