numpy Matplotlib散点图动画

bjp0bcyl  于 2023-05-22  发布在  其他
关注(0)|答案(1)|浏览(89)

我试图在matplotlib中绘制一个动画散点图。
到目前为止我写的代码:

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

我在ValueError: 'vertices' must be a 2D list or array with shape Nx2旁边得到一个空数字
我试着在SO上遵循一些类似的问题,但我找不到我在做什么不同。

ego6inou

ego6inou1#

我已经重新构建了你的动画如下,让我知道如果这是确定的:

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()

相关问题