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?

asked Aug 14, 2016 at 15:54

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()
answered Aug 14, 2016 at 15:59
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.

answered Aug 14, 2016 at 15:59

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.

answered Feb 6, 2019 at 0:16

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.