1、生成随机点阵
# -*- coding:utf-8 -*-
import matplotlib.pyplot as plt
from random import choice
class RandomWalk():
"""一个生成随机漫步数据的类"""
def __init__(self, num_points=5000):
self.num_points = num_points
#定义起始点
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
while len(self.x_values) < self.num_points:
#决定前进方向以及沿这个方向前进的距离
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
if x_step ==0 and y_step == 0: #避免都为零时,原地不动
continue
next_x = self.x_values[-1] + x_step # 计算下一个点的值
next_y = self.y_values[-1] + y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
while True:
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()
keep_running = input("Make another one?(y/n)")
if keep_running == 'n':
break
2、表现出路径
想在加上颜色表明哪部分是先画的点,哪里是后面出现的点,即表现出大致路径。
while True:
rw = RandomWalk()
rw.fill_walk()
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Reds, s=15)
plt.show()
keep_running = input("Make another one?(y/n)")
if keep_running == 'n':
break
3、突出起始点和终点
while True:
rw = RandomWalk()
rw.fill_walk()
point_numbers = list(range(rw.num_points))
plt.scatter(0, 0, c='green', edgecolors='none', s=105)
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, s=15)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=15)
plt.show()
keep_running = input("Make another one?(y/n)")
if keep_running == 'n':
break
4、隐藏坐标轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
5、调整尺寸以适合屏幕
while True:
rw = RandomWalk(5000)
rw.fill_walk()
point_numbers = list(range(rw.num_points))
# figure()指定图表的宽度、高度、分辨率和背景色
plt.figure(dpi=128, figsize=(10, 6))
plt.scatter(0, 0, c='green', edgecolors='none', s=105)
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, s=15)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=15)
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()