Is there a faster way of plotting multiple curves over the same x range than the following?
import numpy as np
import matplotlib.pyplot as plt
N = 100 # trajectories
p = 1e3 # points
x = np.linspace(0, 2*np.pi, p)
y = [np.sin(x)**i for i in range(N)]
color = iter(plt.cm.rainbow(np.linspace(0, 1, N)))
[plt.plot(x, y[i], c=next(color)) for i in range(N)]
plt.show())
This code takes considerable time when plotting many trajectories (N~1e5)
1 Answer 1
I doubt whether you will find a significantly faster solution. You could try to remove the loop around plot
with something like:
N = 200
x = np.linspace(0, 2*np.pi, 1e5)
y = np.array([np.sin(x)**i for i in range(N)])
plt.plot(x, y.transpose()) # I left out the colors for now..
For a small number of lines this seems to be a bit faster, but for your problem size it is exactly as fast/slow as your original solution.
answered Jun 13, 2016 at 12:10
3 Comments
Felix
Thank you for your answer. I was wondering if it would be faster to pass x only once to plt.plot
Felix
Well in your solution x is only passed once to plt.plot()
Bart
Ah, like that.. I just wanted to get rid of the loop around
plot()
, but after looking at the matplotlib source code it looks like the same loop is still there if you pass a 2D array :)lang-py
x = np.linspace(0, 2*np.pi, 1e5)
) seems a bit excessive. On my system 100 points per plot produces lines that are every bit as smooth as the ones with 10,000 points. (Without the slowdown that the large plots cause.)1e5
points per line?