用random.choice完成随机漫步绘图!

今天学习了用random.choice完成随机漫步绘图。
首先,调用random.choice函数。

 from random import choice
    import matplotlib.pyplot as plt
    创建一个随机漫步的类
    class RandomWalk():
   		 #初始化随机漫步的属性
    	def __init__(self, num_points = 5000):
    		self.num_points = num_points
    		self.x_values = x_values
    		self.y_values = y_values
    	
    	def fill_walk(self):
    		while len(self.x_values) < 5000:
    			#定义一个函数,设置随机漫步的方向距离大小
    			#设置x轴的方向距离大小
    			x_directions = [1, -1]
    			x_distance = [0, 1, 2, 3, 4, 5]
    			x_step = x_directions * x_distance
    			#设置y轴方向距离大小
    			y_directions = [1, -1]
				y_distance = [0, 1, 2, 3, 4, 5]
				y_step = y_directions * y_distance
				#禁止原地踏步
				if x_step==0 and y_step==0:
					continue
				#计算下一步的位置
				next_x = self.x_values[-1] + x_step
				next_y = self.y_values[-1] + y_step
				self.x_valuer.append(next_x)
				self.y_values.append(next_y)
	rw = RandomWalk()
	rw.fill_walk()
	plt.scatter(rw.x_values, rw.y_values, c=rw.y_values, cmap=cm.plt.cm.Reds, s=5)
	plt.show()

代码中使用了颜色映射,便于查看。
还可以往其中加入自动保存和输出rw.x_values和rw.y_values列表数据。
以上就是全部代码,有错误请指正,大佬勿喷。
以下是生成的数据图。
在这里插入图片描述在这里插入图片描述在这里插入图片描述
在这里插入图片描述 模拟多次随机,并给点着色

from random import choice
    import matplotlib.pyplot as plt
    创建一个随机漫步的类
    class RandomWalk():
   	 #初始化随机漫步的属性
   		def __init__(self, num_points = 5000):
    		self.num_points = num_points
   			self.x_values = x_values
   			self.y_values = y_values
    	
    	def fill_walk(self):
    		while len(self.x_values) < 5000:
    			#定义一个函数,设置随机漫步的方向距离大小
    			#设置x轴的方向距离大小
    			x_directions = [1, -1]
    			x_distance = [0, 1, 2, 3, 4, 5]
    			x_step = x_directions * x_distance
    			#设置y轴方向距离大小
    			y_directions = [1, -1]
				y_distance = [0, 1, 2, 3, 4, 5]
				y_step = y_directions * y_distance
				#禁止原地踏步
				if x_step==0 and y_step==0:
					continue
				#计算下一步的位置
				next_x = self.x_values[-1] + x_step
				next_y = self.y_values[-1] + y_step
				self.x_valuer.append(next_x)
				self.y_values.append(next_y)
	rw = RandomWalk()
	rw.fill_walk()
	#给点着色
	number_points = list(range(rw.num_points))
	plt.scatter(rw.x_values, rw.y_values, c=number_points, cmap=cm.plt.cm.Reds, s=5)
	plt.show()
	#设置多次随机漫步
	keep_running = input("Make another walk?  (Y/N)")
	if keep_running=='N':
		break

隐藏坐标轴

#隐藏坐标轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)

增加点数

rw.RandomWalk(num_points=50000)

调整尺寸以适合屏幕

plt.figure(dpi=72, figsize=(10, 10))

改进的随机漫步

from random import choice
import matplotlib.pyplot as plt
'''生成一个随机漫步的类'''

class 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_step = self.get_step()
            y_step = self.get_step()

            if x_step==0 and y_step==0:
                continue
            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)

    def get_step(self):
        #设置方向距离大小
        directions = choice([1, -1])
        distance = choice([0, 1, 2, 3, 4])
        return directions * distance

while True:

    rw = RandomWalk(num_points=5000)
    rw.fill_walk()
    plt.figure(num='figure0', dpi=72, figsize=(6, 6))
    numbers_points = list(range(rw.num_points))
    #plt.plot(rw.x_values, rw.y_values, linewidth=0.1)
    plt.scatter(rw.x_values, rw.y_values, s=5, edgecolors='none',
                c=numbers_points, cmap=plt.cm.Blues)
    plt.scatter(0, 0, c='yellow', edgecolor='none', s=20)
    plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolor='none', s=20)

    plt.axes().get_xaxis().set_visible(False)
    plt.axes().get_yaxis().set_visible(False)
    plt.show()
    #plt.savefig("随机漫步.png", bbox_inches='tight')
    print('x:{}'.format(rw.x_values), 'y:{}'.format(rw.y_values), sep='\n\n')
    keep_running = input("Make another walk? (y/n):")

    if keep_running == 'n':
        break

此为重构后的随机漫步,可以缩小fill_walk,是阅读起来更方便。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值