Matplotlib动画不接受圆形补丁作为法格

时间:2018-12-25 18:35:44

标签: python matplotlib

import math
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.patches import Circle
from matplotlib import animation
from utils import rgb2hex
from tg import small_tg

matplotlib.rcParams["figure.figsize"]=(10, 5)
matplotlib.rcParams['toolbar'] = 'None'

fig, ax = plt.subplots()
ax.axis("equal")
ax.set_xlim(-10, 10)
ax.set_ylim(-5, 5)
ax.axis("off")

state_nodes = []
for state in small_tg["states"]:
    center = small_tg["states"][state]["graphic_properties"]["position"]
    state_nodes.append(Circle(center, 0.2, color = rgb2hex(255, 255, 255)))

def animate(i, state):
    print("&", i ,state)
    y = math.ceil((abs(i-100))*2.55)
    print(i, y, (abs(i-100))*2.55)
    state.set_color = rgb2hex(y,y,y)
    ax.add_artist(state)
    return state,

for state in state_nodes:
    print(state)
    animation.FuncAnimation(fig, animate, fargs = (state,), frames=201, interval=1, blit=True, repeat = False)

plt.show()

for循环内的print语句显示状态,但是animate函数内的print语句不显示任何内容,这意味着未调用该函数。我找不到任何逻辑错误。请帮忙。

1 个答案:

答案 0 :(得分:1)

如果要一起动画多个元素,则不应运行多个FuncAnimation。而是运行一个动画,并通过单个animate()函数为所有艺术家设置动画。

我无法为您运行代码,但是我试图保持与我在本演示中对您的代码的理解接近:

import math
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib import animation
from matplotlib.colors import rgb2hex

fig, ax = plt.subplots()
ax.axis("equal")
ax.set_xlim(-10, 10)
ax.set_ylim(-5, 5)
ax.axis("off")

state_nodes = [Circle(center, 0.2, color='k') for center in np.random.normal(loc=0, scale=1, size=(5,2))]
for state in state_nodes:
    ax.add_artist(state)

def animate(i, states):
    c = (i/255)
    for state in states:
        dx,dy = np.random.normal(loc=0, scale=0.1, size=(2,))
        x,y = state.get_center()
        state.set_center((x+dx,y+dy))
        state.set_color(rgb2hex((c,c,c)))
    return states


ani = animation.FuncAnimation(fig, animate, fargs = (state_nodes,), frames=201, interval=25, blit=True, repeat = False)
plt.show()

enter image description here