'want to plot more than 2 randomwalk in same graph with different color,but with every new randomwalks, previous random walk plot is removed
This is my module I made for random walk of a man for each step 1,-1 direction and up to 4 m distance, and up to 20 steps the coordinates will save in x_label and Y_label '''
from random import choice
class RandomWalks:
def __init__(self, num_point=20):
self.numpoints = num_point
self.x_label = [0]
self.y_label = [0]
def fill_walk(self):
"""Calculate all the points in the walk."""
# Keep taking steps untill the walk reaches the desired length.
while len(self.x_label) < self.numpoints:
"Decide which direction to go and how far to go in that direction."
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = choice([0, 1, 2, 3, 4])
y_step = y_direction * y_distance
# Reject moves that go nowhere.
if x_step == 0 and y_step == 0:
continue
# Calculate the next x and y values.
next_x = self.x_label[-1] + x_step
next_y = self.y_label[-1] + y_step
self.x_label.append(next_x)
self.y_label.append(next_y)
''' My code is running fine but, there is one problem coming, I want to start the next random walk every time I type yes when it asks keep_running, it should start a different random walk plot in the same previous plot that is why I plotted the line with different colour when more than one random walk occur \n *But, what happening is everytime I type 'y' to keep_running, it delete the previous plotted data and make new one different plot line * '''
from random_walks import RandomWalks as rm
import matplotlib.pyplot as plt
rw = rm()
colors = ['blue', 'red', 'purple', 'orange']
count = -1
keep_running = 'y'
while keep_running == 'y':
# Make a random walk, and plot the points.
rw.fill_walk()
plt.xlabel("x-cordinate", fontsize="14")
plt.ylabel("y-cordinate", fontsize="14")
plt.title("Random-walk", fontsize=24)
plt.axis([-50, 50, -50, 50])
count = count + 1
if keep_running == 'y':
plt.plot(rw.x_label, rw.y_label, color=colors[count])
point_numbers = list(range(rw.numpoints))
plt.scatter(0, 0, c="green", s=30)
plt.scatter(rw.x_label[-1], rw.y_label[-1], c="red", s=30)
plt.scatter(rw.x_label, rw.y_label, c=point_numbers, cmap=plt.cm.pink,edgecolors="none", s=50)
plt.show()
else:
break
keep_running = input("Make another walk ?(y/n): \t")
'''
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
