温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在Python中使用matplotlib绘制漫步图

发布时间:2021-03-26 16:33:08 来源:亿速云 阅读:112 作者:Leah 栏目:开发技术

这期内容当中小编将会给大家带来有关怎么在Python中使用matplotlib绘制漫步图,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

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_distance * x_direction 
 
  y_direction = choice([-1, 1])
  y_distance = choice([0, 1, 2, 3, 4])
  y_step = y_distance * y_direction
 
  # 拒绝原地踏步
  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)
from random_walk import RandomWalk
 
# 不断的模拟随机漫步
while True:
 # 创建一个RandomWalk实例,将其包含的点绘制出来
 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.Blues, 
 edgecolor = 'none', s = 5)
 
 # 突出起点和终点
 plt.scatter(0, 0, c='green', edgecolors = 'none', s = 100)
 plt.scatter(rw.x_values[1], rw.y_values[-1], c = 'red', edgecolors = 'none', s = 100)
 
 # 隐藏坐标轴
 # 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.lower().startswith('n'):
 break

上述就是小编为大家分享的怎么在Python中使用matplotlib绘制漫步图了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI