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
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()
1 Comment
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
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.