代码之家  ›  专栏  ›  技术社区  ›  Dhruv Chadha

Matplotlib动画不接受圆补丁作为Fargs

  •  1
  • Dhruv Chadha  · 技术社区  · 5 年前
    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 回复  |  直到 5 年前
        1
  •  1
  •   Diziet Asahi    5 年前

    如果要将多个元素一起设置动画,则不应运行多个 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