The Imp The Imp - 1 month ago 4x
Python Question

How to plot 2D object in python?

I want to create an animation in which a box will move on a specified track.

Is there way to accomplish this task in python?
Also is there boolean plot function in matplotlib which can allow one to explicitly draw pixels?


I'm going to adapt from this answer (from @unutbu). The following code builds a square trajectory and moves a rectangle with it:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib import animation

# Building a possible trajectory
x = np.hstack((np.linspace(-5, 5, 50), np.ones(50)*5, np.linspace(5, -5, 50), np.ones(50)*-5))
y = np.hstack((np.ones(50)*-5, np.linspace(-5, 5, 50), np.ones(50)*5, np.linspace(5, -5, 50)))

yaw = [0.0, 0.5, 1.3]
fig = plt.figure()
ax = fig.add_subplot(111)

# Adding a simple plot for trajectory (initial coordinate of rectangle)
ax.plot([-5, 5, 5, -5, -5], [-5, -5, 5, 5, -5], color="grey", linestyle="--")

ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)

patch = patches.Rectangle((0, 0), 0, 0, fc='y')

def init():
    return patch,

def animate(i):
    patch.set_xy([x[i], y[i]])
    return patch,

anim = animation.FuncAnimation(fig, animate,

, the result is this (well just a screenshot, its actually animated):

Square animation in matplotlib

As for your other question, matplotlib is not pixel based so I don't think you have a (easy) way of drawing just one pixel. Depending on your objective you light want to consider using the well supported image api in matplotlib to provide you with customized backgrounds. So you would be drawing in arrays that would be parsed to the screen by matplotlib.