Mathew
Mathew

Reputation: 1430

matplotlib scatter takes too long

Consider the following code which produces a random sequence of dots of various colours.

import matplotlib.pyplot as plt
import random

n = 100

x = [0]*n
y = [0]*n
col=['red']*n


for i in range(1,n): 
    val = random.randint(1,2)
    if val == 1: 
        col[i] = 'red'
    if val == 2: 
        col[i] = 'yellow'

ax=plt.figure().add_subplot()
for i in range(n):
    ax.scatter(i,0, color=col[i])
    #print(x[i],y[i],col[i])
plt.show()

Right now it does 100 point, however I would like it to do 10000 points. Doing this takes too long however, how can I make this faster? Thanks

Upvotes: 1

Views: 365

Answers (1)

Sheldore
Sheldore

Reputation: 39052

Avoid the unnecessary for loop for plotting n scatter points one at a time. Instead, plot the whole range at once and pass the whole col list for colors

fig = plt.figure()
ax = fig.add_subplot(111)

ax.scatter(range(n), [0]*n, color=col)
plt.show()

Upvotes: 4

Related Questions