Python繪製隨機漫步圖

  最近開始學習Python,由於是在jupyter在線練習,所以創建類和可視化操作都放在同一文件中運行。  
  需要注意的是,Python中單下劃線和雙下劃線的使用區別以及格式的對齊,Python是根據對齊方式自動區分代碼塊的,我個人在運行過程中主要出現的問題就是這兩個方面。

代碼:

import matplotlib.pyplot as plt   
from random import choice
class RandomWalk():
    #這裏注意是雙下劃線
    def __init__(self, num_points=5000):       
            self.num_points = num_points
        # 所有隨機漫步都始於(0,0)
        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([1, 2, 3, 4])
            x_step = x_direction * x_distance

            y_direction = choice([1, -1])
            y_distance = choice([1, 2, 3, 4])
            y_step = y_direction * y_distance

            # 拒絕原地踏步
            if x_step == 0 and y_step == 0:
                continue

            # 計算下一個點的x和y值
            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)
            
# 創建一個RandomWalk實例,並將其包含的點都繪製出來
rw = RandomWalk(5000)
rw.fill_walk()
  
# 設置繪圖窗口的尺寸
plt.figure(dpi=80,figsize=(10,6))
  
# 設置點按先後順序增加顏色深度
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values,rw.y_values,c=point_numbers,cmap=plt.cm.Blues,edgecolor='none',s=3)
  
# 突出起點和終點,起點設置爲綠色,終點設置爲紅色
plt.scatter(0,0,c='green',edgecolor='none',s=100)
plt.scatter(rw.x_values[-1],rw.y_values[-1],c='red',edgecolor='none',s=100)
  
# 隱藏座標軸
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()

運行結果圖:

運行結果圖

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章