Python数据可视化之随机点图
生活随笔
收集整理的這篇文章主要介紹了
Python数据可视化之随机点图
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python數據可視化之隨機點圖
使用Python來生成隨機漫步數據,再使用matplotlib將這些數據呈現出來。 隨機漫步是這樣行走得到的路徑:每次行走都完全是隨機的,沒有明確的方向,結果是由一系列隨機決策決定的 。
創建 RandomWalk()類
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Date : 2020-11-13 16:20:44 # @Author : EricRay # @Email : ericray.tech@outlook.com # @Link : https://blog.csdn.net/ericleiy/ # @Description : 隨機生成所有可能存在的點from random import choiceclass 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]) # 1 向右 -1向左x_distance = choice([1, 2, 3, 4]) # 隨機選擇0-4之間的整數x_step = x_direction * x_distancey_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_stepnext_y = self.y_values[-1] + y_stepself.x_values.append(next_x)self.y_values.append(next_y)繪制隨機漫步圖
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Date : 2020-11-13 16:32:38 # @Author : EricRay # @Email : ericray.tech@outlook.com # @Link : https://blog.csdn.net/ericleiy/ # @Descriptionimport matplotlib.pyplot as pltfrom random_walk import RandomWalk# 不斷模擬 while True:# 創建一個RandomWalk實例,繪制所有的點rw = RandomWalk()rw = RandomWalk(50000) # 增加點數rw.fill_walk()# plt.scatter(rw.x_values, rw.y_values, s=15)# 設置繪圖窗口的尺寸# plt.figure(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,edgecolors='none', s=10)# 突出起點和終點plt.scatter(0, 0, c='green', edgecolors='none', s=50) # 起點plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red',edgecolors='none', s=50) # 終點# 隱藏坐標軸plt.axes().get_xaxis().set_visible(False)plt.axes().get_yaxis().set_visible(False)plt.show()# 可打印多張圖keep_running = input("Make another walk? (y/n): ")if keep_running == 'n':break效果圖:
總結
以上是生活随笔為你收集整理的Python数据可视化之随机点图的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 仿真软件 JaamSim介绍
- 下一篇: C++实验八——类的继承(2)