Home > Net >  Matplotlib scatterplot animation
Matplotlib scatterplot animation

Time:09-17

I am trying to plot an animated scatter plot in matplotlib.

The code I wrote so far:

import math
import sympy
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as ani

def convert_to_polar_coordinates(num):
    return num * np.cos(num), num * np.sin(num)


fig = plt.figure(figsize=(8, 8))
primes = sympy.primerange(0, 15000)
primes = np.array(list(primes))
x, y = convert_to_polar_coordinates(primes)
scat = plt.scatter([],[],s=1)

def init():
    scat.set_offsets([])
    return scat,

def plot_in_polar(i=int):
    data = np.hstack((x[:i,np.newaxis], y[:i, np.newaxis]))
    scat.set_offsets(data)
    return scat,

plt.axis("off")
animator = ani.FuncAnimation(fig, plot_in_polar, init_func=init, interval = 20)
plt.show()

animator.save(r'D:\primes.gif')

I get an empty figure alongside a ValueError: 'vertices' must be a 2D list or array with shape Nx2

I tried to follow a few similar questions on SO but I can't find what I am doing differently.

CodePudding user response:

I have re-structured you animation as follow, let me know if that's ok:

import sympy
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as ani


def convert_to_polar_coordinates(num):
    return num*np.cos(num), num*np.sin(num)


lim = 5000

fig, ax = plt.subplots(figsize = (8, 8))
primes = sympy.primerange(0, lim)
primes = np.array(list(primes))
x, y = convert_to_polar_coordinates(primes)


def init():
    ax.cla()
    ax.plot([], [])


def plot_in_polar(i):
    ax.cla()
    ax.plot(x[:i], y[:i], linestyle = '', marker = 'o', markersize = 1)
    ax.set_xlim(-lim, lim)
    ax.set_ylim(-lim, lim)
    ax.axis("off")


animator = ani.FuncAnimation(fig = fig, func = plot_in_polar, interval = 20, frames = len(primes))

plt.show()

enter image description here

  • Related