I'm programming a random walk simulator in a JupyterLab Notebook. With a for loop, I want the simulator to generate multiple datasets that are then plotted on a single figure. I managed to do this. Here's my code (including the code for the random walk simulator):
#RANDOM WALK SIMULATOR
import matplotlib.pyplot as plt
import numpy as np
def random_walk(random_state_index, initial_position=(0, 0), steps=1000):
np.random.RandomState(random_state_index)
X, Y = [initial_position[0]], [initial_position[0]]
for i in range(steps):
plt.pause(0.00001)
# Random step choice
ways = ["up", "down", "left", "right"]
direction = np.random.choice(ways, p = [0.3,0.2,0.25,0.25])
if direction == "up":
X.append(X[-1])
Y.append(Y[-1] + 0.1)
if direction == "down":
X.append(X[-1])
Y.append(Y[-1] - 0.1)
if direction == "left":
X.append(X[-1] - 0.1)
Y.append(Y[-1])
if direction == "right":
X.append(X[-1] + 0.1)
Y.append(Y[-1])
return X,Y
#PLOT
fig, ax = plt.subplots()
for i in range(10):
X,Y = random_walk(random_state_index = i)
ax.plot(X,Y)
fig
Ahead is a link that shows what my output looks like. As you can see, I get an extra, empty plot. I'd like to get rid of it, but I'm having difficulty finding out how: OUTPUT
Thank you!
SOLUTION: I found a solution without resorting to interactive mode. Here's the solution:
%matplotlib inline
plt.show(block = True)
fig, ax = plt.subplots()
for i in range(10):
X,Y = random_walk(random_state_index = i)
ax.plot(X,Y)