Search code examples
pythonmatplotlibplotvectorization

Vectorizing matplotlib axes


I am trying to avoid using "for" loops in some matplotlib plots. For this, I have tried the following code:

t=np.linspace(0,1,1000)
signals=[]

for k in range(8):  
    signals.append(np.sin(2*np.pi*t*k))
signals=np.array(signals)
    
units=np.array(['V', 'V', 'V', 'V', 'A', 'A', 'A', 'A'])
fig, axes = plt.subplots(8, 1,figsize=(10, 16))
# axes.plot(t,signals[units=="V",:])

The last commented line throws an error, because axes is a numpy array, which has no attribute "plot". I was trying to assign each axe to the plot of each signal.

How can I make this line with vectorization?

Thanks.


Solution

  • You cannot vectorize the creation of multiple subplots, but you can use a loop:

    fig, axes = plt.subplots(signals.shape[0], 1, figsize=(8, signals.shape[0] * 2.5))
    
    for i in range(signals.shape[0]):
        axes[i].plot(signals[i, ...])
        axes[i].set_ylabel('x(t) (unit: V)')
        ...
    

    What you can do is plot everything into the same axes (simply use ax.plot(signals.T)).