import matplotlib.pyplot as plt |
import random |
import numpy as np |
# 定义函数 |
def random_walk(n): |
x = 0 |
y = 0 |
x_list = [] |
y_list = [] |
for i in range (n): |
step = np.random.randint( 1 , 5 ) |
if step = = 1 : |
x + = 50 |
elif step = = 2 : |
y + = 50 |
elif step = = 3 : |
x - = 50 |
else : |
y - = 50 |
x_list.append(x) |
y_list.append(y) |
return x_list, y_list |
# 绘制蚂蚁随机漫步图 |
n = 30000 # 随机漫步次数 |
# 第1只蚂蚁 |
x_list, y_list = random_walk(n) |
plt.scatter(x_list, y_list, c = range (n), vmin = 0 , vmax = 20000 , s = 1 , cmap = plt.cm.get_cmap( 'PuBuGn' )) |
plt.xlim(( - 10000 , 10000 )) |
plt.ylim(( - 10000 , 10000 )) |
# 第2只蚂蚁 |
x_list, y_list = random_walk(n) |
plt.scatter(x_list, y_list, c = range (n), vmin = 0 , vmax = 20000 , s = 1 , cmap = plt.cm.get_cmap( 'RdYlBu_r' )) |
# 第3只蚂蚁 |
x_list, y_list = random_walk(n) |
plt.scatter(x_list, y_list, c = range (n), vmin = 0 , vmax = 20000 , s = 1 , cmap = plt.cm.get_cmap( 'YlGnBu' )) |
plt.show() |