4

I have the following python script:

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(123)

initialize and populate all_walks

all_walks = [] for i in range(5) : random_walk = [0] for x in range(100) : step = random_walk[-1] dice = np.random.randint(1,7) if dice <= 2: step = max(0, step - 1) elif dice <= 5: step = step + 1 else: step = step + np.random.randint(1,7) random_walk.append(step) all_walks.append(random_walk)

Convert all_walks to NumPy array: np_aw

np_aw = np.array(all_walks)

Plot np_aw and show

plt.plot(np_aw) plt.show()

Clear the figure

plt.clf()

Transpose np_aw: np_aw_t

np_aw_t =np.transpose(np_aw)

Plot np_aw_t and show

plt.plot(np_aw_t) plt.show() plt.clf()

I am trying to simulate a random walk and plot the graphs as you can see. The first plot looks like this : plot of np_aw (array not transposed)

The second one is this :

plot of np_aw (after transpose)

Clearly the correct image I was meaning to plot is the second but I didn't understand why I need to transpose the array ? and what does the first image represent ? I know it seems trivial but I don't want to skip over it without understanding what each one represents. Thanks for Any help in advance.

JouJour
  • 91
  • 4

1 Answers1

3

So for you, matplotlib is interpreting this as "plot each row as a separate series". You have a 2d array of [5, 101], which is getting interpreted as 5 y-series, each with 101 values. This is equivalent to the following:

for col in range(np_aw.shape[1]):
    plt.plot(np_aw[:, col])

So what does the first graph mean? Well, it represents the position of the 5 walkers, but shows their position as a separate series. np_aw[:, 0] is [0, 0, 0, 0, 0]. This is why you see that blue line going across all 0's, and then changes over time. If you look at np_aw[:, -1] you'll see [60, 73, 83, 68, 73]. Basically you're just getting the positions as separate lines. Maybe that's helpful if you're trying to see how much difference there is at different time steps across the 5 walkers.

The reason transposing works is you then get a shape of [101, 5] and now assumes the x goes from [0, 100] and each has 5 lines.

Chrispresso
  • 221
  • 1