Python Tales - The Python Tutor Blog

A Python Programming Blog, from a Pythoneer to Pythoneers, created by The Python Tutor.

Monday, August 28, 2017

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

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],

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')
    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])


current_pacman = pacman

dx = 0.5
dy = 0.0
pacman_center = [1.52.5]

for i in range(200):

    if animate() == (00):

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.