Python编程:从入门到实践 - matplotlib篇 - Random Walk
随机漫步
# random_walk.py 随机漫步 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([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 # 计算下一个点的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)
# rw_visual.py 随机漫步实现
import matplotlib.pyplot as plt
import random from random_walk import RandomWalk # 只要程序处于活动状态,就不断地模拟随机漫步
while True:
# 创建一个RandomWalk实例,并将其包含的点都绘制出来
rw = RandomWalk(50000)
rw.fill_walk() # 设置绘图窗口的尺寸
plt.figure(figsize=(10, 6)) # 映射
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, edgecolors='none', s=1, c=point_numbers, cmap=plt.cm.Blues) # 突出起点和终点
plt.scatter(0, 0, c='green', edgecolors='none', s=5)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=5) # 设置坐标轴的标签以及标题
plt.xlabel('Axis X', fontsize=14)
plt.ylabel('Axis Y', fontsize=14)
plt.title('Random Walk', fontsize=24) # 隐藏坐标轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False) # 显示
#plt.show() # 保存图表
filename = 'rw_' + str(random.randint(000000, 999999)) + '.png'
plt.savefig('images/' + filename, bbox_inches='tight') # 不可既使用show显示,又使用svaefig保存,否则保存图像为空 # 询问是否继续
flag = input('Make another walk? (y/n):')
if flag.lower() not in ['y', 'yes']:
break
Python编程:从入门到实践 - matplotlib篇 - Random Walk的更多相关文章
- Python编程:从入门到实践 - matplotlib篇 - Random Flow
随机漫游 # random_flow.py 随机漫游 import random class RandomFlow(): """一个生成随机漫游数据的类"&qu ...
- 《Python编程:从入门到实践》分享下载
书籍信息 书名:<Python编程:从入门到实践> 原作名:Python Crash Course 作者: [美] 埃里克·马瑟斯 豆瓣评分:9.1分(2534人评价) 内容简介 本书是一 ...
- Python编程从入门到实践笔记——异常和存储数据
Python编程从入门到实践笔记——异常和存储数据 #coding=gbk #Python编程从入门到实践笔记——异常和存储数据 #10.3异常 #Python使用被称为异常的特殊对象来管理程序执行期 ...
- Python编程从入门到实践笔记——文件
Python编程从入门到实践笔记——文件 #coding=gbk #Python编程从入门到实践笔记——文件 #10.1从文件中读取数据 #1.读取整个文件 file_name = 'pi_digit ...
- Python编程从入门到实践笔记——类
Python编程从入门到实践笔记——类 #coding=gbk #Python编程从入门到实践笔记——类 #9.1创建和使用类 #1.创建Dog类 class Dog():#类名首字母大写 " ...
- Python编程从入门到实践笔记——函数
Python编程从入门到实践笔记——函数 #coding=gbk #Python编程从入门到实践笔记——函数 #8.1定义函数 def 函数名(形参): # [缩进]注释+函数体 #1.向函数传递信息 ...
- Python编程从入门到实践笔记——用户输入和while循环
Python编程从入门到实践笔记——用户输入和while循环 #coding=utf-8 #函数input()让程序暂停运行,等待用户输入一些文本.得到用户的输入以后将其存储在一个变量中,方便后续使用 ...
- Python编程从入门到实践笔记——字典
Python编程从入门到实践笔记——字典 #coding=utf-8 #字典--放在{}中的键值对:跟json很像 #键和值之间用:分隔:键值对之间用,分隔 alien_0 = {'color':'g ...
- Python编程从入门到实践笔记——if语句
Python编程从入门到实践笔记——if语句 #coding=utf-8 cars=['bwm','audi','toyota','subaru','maserati'] bicycles = [&q ...
随机推荐
- ZOJ 3209
精确覆盖 #include <iostream> #include <cstdio> #include <cstring> #include <algorit ...
- event.currentTarget与event.target的差别介绍
event.currentTarget与event.target的差别想大家在使用的时候不是非常在意.本文以測试代码来解说它门之间的不同.即,event.currentTarget指向事件所绑定的元素 ...
- HDU2955_Robberies【01背包】
Robberies Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total ...
- 随机获取一个集合(List, Set)中的元素,随机获取一个Map中的key或value
利用Java提供的Random类.从List或Set中随机取出一个元素,从Map中随机获取一个key或value. 因为Set没有提供get(int index)方法,仅仅能先获取一个随机数后.利用一 ...
- luogu1445 [violet]樱花 阶乘分解
题目大意 求方程$$\frac{1}{x}+\frac{1}{y}=\frac{1}{N!}$$的正整数解的组数. 思路 咱们把式子整理得$$xy-(x+y)N!=0$$.$xy$和$x+y$?貌似可 ...
- BZOJ 1951 Lucas定理+CRT
思路: 枚举约数 套个裸的Lucas+CRT就完了... //By SiriusRen #include <cmath> #include <cstdio> using nam ...
- BZOJ 2073
思路: 状压DP 枚举子集 //By SiriusRen #include <cstdio> #include <cstring> #include <algorith ...
- A - Translation
Problem description The translation from the Berland language into the Birland language is not an ea ...
- Spark Scala语言学习系列之完成HelloWorld程序(三种方式)
三种方式完成HelloWorld程序 分别采用在REPL,命令行(scala脚本)和Eclipse下运行hello world. 一.Scala REPL. windows下安装好scala后,直接C ...
- mysql5.7 设置密码
5.7版本的MYSQL的用户表的密码字段与以往版本有所区别, 不再是password字段 而是authentication_string字段. 请注意修改密码: vim /opt/mysql_d/m ...