1、生成隨機點陣
# -*- coding:utf-8 -*-
import matplotlib.pyplot as plt
from random import choice
class RandomWalk():
"""一個生成隨機漫步數(shù)據(jù)的類"""
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习绢、表現(xiàn)出路徑
想在加上顏色表明哪部分是先畫的點,哪里是后面出現(xiàn)的點蝙昙,即表現(xiàn)出大致路徑闪萄。
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败去、調(diào)整尺寸以適合屏幕
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()