0

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)

asked Jun 13, 2016 at 10:31
2
  • Use less points per plot? 10,000 (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.) Commented Jun 13, 2016 at 11:38
  • The point remains though - do you really need 1e5 points per line? Commented Jun 13, 2016 at 11:56

1 Answer 1

2

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

Thank you for your answer. I was wondering if it would be faster to pass x only once to plt.plot
Well in your solution x is only passed once to plt.plot()
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 :)

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.