Python数据可视化之随机点图
生活随笔
收集整理的這篇文章主要介紹了
Python数据可视化之随机点图
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Python數(shù)據(jù)可視化之隨機(jī)點(diǎn)圖
使用Python來生成隨機(jī)漫步數(shù)據(jù),再使用matplotlib將這些數(shù)據(jù)呈現(xiàn)出來。 隨機(jī)漫步是這樣行走得到的路徑:每次行走都完全是隨機(jī)的,沒有明確的方向,結(jié)果是由一系列隨機(jī)決策決定的 。
創(chuàng)建 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 : 隨機(jī)生成所有可能存在的點(diǎn)from random import choiceclass RandomWalk():"""一個(gè)生成隨機(jī)漫步數(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):"""計(jì)算隨機(jī)漫步包含的所有點(diǎn)"""# 不斷漫步,直到列表達(dá)到的指定長度while len(self.x_values) < self.num_points:# 決定前進(jìn)方向及前進(jìn)的距離x_direction = choice([1, -1]) # 1 向右 -1向左x_distance = choice([1, 2, 3, 4]) # 隨機(jī)選擇0-4之間的整數(shù)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# 計(jì)算下一個(gè)點(diǎn)的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)繪制隨機(jī)漫步圖
#!/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:# 創(chuàng)建一個(gè)RandomWalk實(shí)例,繪制所有的點(diǎn)rw = RandomWalk()rw = RandomWalk(50000) # 增加點(diǎn)數(shù)rw.fill_walk()# plt.scatter(rw.x_values, rw.y_values, s=15)# 設(shè)置繪圖窗口的尺寸# plt.figure(figsize=(10, 6))# 設(shè)置隨機(jī)漫步圖的樣式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)# 突出起點(diǎn)和終點(diǎn)plt.scatter(0, 0, c='green', edgecolors='none', s=50) # 起點(diǎn)plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red',edgecolors='none', s=50) # 終點(diǎn)# 隱藏坐標(biāo)軸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效果圖:
總結(jié)
以上是生活随笔為你收集整理的Python数据可视化之随机点图的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 仿真软件 JaamSim介绍
- 下一篇: python自学行吗知乎_怎么自学pyt