Simple animation of 2D coordinates using matplotli

2019-02-17 04:26发布

问题:

I am new to matplotlib. I have a list of x-y coordinates that I update in python and want to animate using matplotlib's pyplot. I want to specify the x-range and y-range in advance. Below is my current code:

import matplotlib.pyplot as plt
x=[1,2,3,4]
y=[5,6,7,8]
for t in range(100):
    #lists x and y get updated here
    #...
plt.plot(x, y, marker='o', linestyle='None')
plt.show()

As you can see, I use plt.plot() and plt.show() at the end of my iteration loop to plot only the final coordinates. But I want to put this step inside the loop and plot at every iteration with a specified pause time so that I have an animation as the loop runs.

Just moving that statement inside the loop or tweaks thereabout aren't working. I want to keep it very simple though, and don't want to use matplotlib.animation. Is there some simple method without using many more modules and libraries (only stuff like plt.pause() and perhaps only a bit more) that will let me do what I want?

I looked at many places online, and the problem I face with most methods there is that I am using python(x,y) (that's python version 2.7) on Windows for this, and animations using too complicated modules and libraries are crashing here.

However, I am able to run simple stuff like this example on the matplotlib site, which is close to what I want, but not quite. So perhaps the best thing will be a modification of this example that works for my case of 2D data (that example is for a 1D row). But any other suggestion is welcome.

回答1:

This is adapted from the animation demo:

import matplotlib.pyplot as plt 
import numpy as np

fig, ax = plt.subplots()

x = [1, 2, 3, 4]
y = [5, 6, 7, 8]

for t in range(10):
    if t == 0:
        points, = ax.plot(x, y, marker='o', linestyle='None')
        ax.set_xlim(0, 10) 
        ax.set_ylim(0, 10) 
    else:
        new_x = np.random.randint(10, size=5)
        new_y = np.random.randint(10, size=5)
        points.set_data(new_x, new_y)
    plt.pause(0.5)

While this is simple the docstring say that it is slow.