2

I was wondering if someone could explain to me what do the , commas do in the line

    P, = ax.plot([],[])
    Q, = ax.plot([],[])
    Qa, =ax.plot([],[])

When I use the code without these commas I get an error explaining to me that lists do not have the set_data attribute. I have been trying to decipher it all morning but so far have been unable to. The complete code is below. It is part of small program to run a brief animation. Thanks for all your help.

    from math import cos, sin , pi
    from matplotlib import pyplot as plt
    import numpy as np
    from matplotlib import animation as anim

    theta = np.linspace(0,2*pi, 100)
    #psi = pi/3
    a = 2
    b = 1
    x = []
    y = []

    for angle in theta:
        x.append(a*cos(angle))
        y.append(b*sin(angle))

    fig = plt.figure(figsize=(8,8), dpi=80)
    plt.subplot(111)
    ax = plt.axes(xlim =(-2.5, 2.5), ylim = ( -2.5, 2.5))
    plt.plot(x,y)
    P, = ax.plot([],[])
    Q, = ax.plot([],[])
    Qa, =ax.plot([],[])
    #plt.plot([0,a*cos(psi)],[0,b*sin(psi)], label = "P")
    #plt.plot([0,a*cos(psi + pi/2)],[0,b*sin(psi + pi/2)], label = "Q")
    #plt.plot([0, a*cos(psi-pi/2)],[0,b*sin(psi- pi/2)], label = "Q'")
    plt.legend()

    def update(frame):
        psi = pi*frame/ 100
        P.set_data([0,a*cos(psi)],[0,b*sin(psi)])
        Q.set_data([0,a*cos(psi + pi/2)],[0,b*sin(psi + pi/2)])
        Qa.set_data([0, a*cos(psi-pi/2)],[0,b*sin(psi- pi/2)])

        return P, Q, Qa

    def init():
        P.set_data([],[])
        Q.set_data([],[])
        Qa.set_data([],[])
        return P, Q, Qa

    animation = anim.FuncAnimation(fig, update, interval=10, blit= False, init_func = init, frames=200)
    # animation.save('rain.gif', writer='imagemagick', fps=30, dpi=40)
    plt.show()
  • It doesn't mean anything special in the specific context. This is colloquially called "unpacking", i.e. extracting element(s) from a container expression to the right-hand side of `=`. – Cong Ma Feb 26 '18 at 11:44

1 Answers1

7

ax.plot() returns a tuple which contains only one element. If you assign it without the comma, you just assign the tuple.

>>> t = (1,)
>>> a = t
>>> a
(1,)

But if you assign it with the comma, you unpack it.

>>> t = (1,)
>>> a, = t
>>> a
1
jsmolka
  • 780
  • 6
  • 15