Search code examples
pythonnumpymatplotlibunpack

Unpacking first dimension of NumPy array into pyplot.plot


I have five sets of x,y data I'd like to plot in a single plt.plot() command by unwrapping the first dimension only of my array (of shape (5,2,500). If I try:

plt.plot(*arr)

I get the error

ValueError: third arg must be a format string

but if I plot by sending the x,y pairs separately, it works. e.g. for three lines:

plt.plot(arr[0][0], arr[0][1], arr[1][0], arr[1][1], arr[2][0], arr[2][1])

How can I unpack the first dimension only into the argument list for pt.plot?


Solution

  • plt.plot(*arr)
    

    is equivalent to

    plt.plot(arr[0], arr[1], arr[2], arr[3], arr[4])
    

    That's why it does not work.

    As @M4rtini wrote in their comment, you can do plt.plot(arr[:,0,:].T, arr[:,1,:].T).

    plt.plot(X, Y) creates a separate plot for each column in X and Y. Thus, arr[:, 0] and arr[:, 1] extract blocks of x and y coordinates, and .T transposes the blocks so that the first dimension goes into the columns.