如何用python绘制二维随机游动图?

2024-10-01 15:39:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了二维随机游动的代码:

def r2walk(T):
    x = np.zeros((T))
    y = np.zeros((T))
    x = [0]*T
    y = [0]*T
    for t in range(0,T):
        walk = random.random()
        if 0 < walk < .25:
            x[t] = x[t-1] + 1
        elif .25 < walk < .5:
            x[t] = x[t-1] - 1
        elif .5 < walk < 0.75:
            y[t] = y[t-1] + 1
        else:
            y[t] = y[t-1] - 1
     return x, y

我希望能够在x,y网格上绘制随机行走的路径,但不确定如何继续。另外,我对python还很陌生,如果有任何关于更高效地编写代码的提示,我将不胜感激。提前谢谢你!在


Tags: 代码in网格forreturnifdefnp
1条回答
网友
1楼 · 发布于 2024-10-01 15:39:09

你需要使用一些绘图软件包。最常用的是matplotlib,它与numpy配合得非常出色。在

那么您的代码看起来像:

import matplotlib.pyplot as plt
import numpy as np
import random

def r2walk(T):
    x = np.zeros((T))
    y = np.zeros((T))
    for t in range(0,T):
        walk = random.random()
        if 0 < walk < .25:
            x[t] = x[t-1] + 1
        elif .25 < walk < .5:
            x[t] = x[t-1] - 1
        elif .5 < walk < 0.75:
            y[t] = y[t-1] + 1
        else:
            y[t] = y[t-1] - 1
    return x, y



x, y = r2walk(100)

# create a figure
fig = plt.figure()
# create a plot into the figure
ax = fig.add_subplot(111)
# plot the data
ax.plot(x,y)

这将为您提供:

enter image description here

如果您对matplotlib完全陌生,我建议您看看IPython和{},当然还有一些{}教程。你可以用一百万种不同的方式来描绘你的行走。在

相关问题 更多 >

    热门问题