10

I have two numpy arrays (a and b) with shape (16, 850) each. I'm displaying them row by row, e.g.

plt.figure()
plt.plot(a[0], b[0])
plt.plot(a[1], b[1]) 
plt.plot(a[2], b[2])
...
plt.show()

Should I have to use a for loop to do it in a more pythonic way?

3 Answers 3

16

You can pass a multi-dimensional array to plot and each column will be created as a separate plot object. We transpose both inputs so that it will plot each row separately.

a = np.random.rand(16, 850)
b = np.random.rand(16, 850)

plt.plot(a.T, b.T)
plt.show()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Suever. That worked because I needed to display 16 plots. That's why I said "row by row" :)
0

This will work:

plt.figure()
for i in range(len(a)):
    plt.plot(a[i], b[i])
plt.show()

But the way that Suever shows is much Pythonic. However, not every function has something like that built-in.

Comments

0

The most efficient way to draw many lines is the use of a LineCollection. This might look like

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

x = np.random.rand(N,3)
y = np.random.rand(N,3)

data = np.stack((x,y), axis=2)
fig, ax = plt.subplots()

ax.add_collection(LineCollection(data))

for a bunch of lines consisting of 3 points each.

Find a comparisson for different methods and their efficiency in the answer to Many plots in less time - python.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.