【问题标题】:Problems plotting a 2D random walk with Python使用 Python 绘制 2D 随机游走的问题
【发布时间】:2014-12-03 22:24:12
【问题描述】:

我正在尝试使用 Python 创建 2D 随机游走。随机游走发生在正方形内,如果粒子穿过正方形的任何一侧,粒子就会出现在另一侧——实际上,随机游走发生在圆环上。

这是我的代码的副本:

from random import randrange as rand
from math import cos, sin, radians
import matplotlib.pyplot as plt

N = 100   # Size of square as a multiple of the step size.
NSteps = 5000   # Number of steps in simulation.
xStart = 0   # x coordinate of starting location. Origin is at centre of square
yStart = 0   # y coordinate of starting location. Origin is at centre of square

s = 1   # Step number.
x = xStart   # x coordinate of point.
y = yStart   # y coordinate of point.
xList = []   # List of the x coordinates of all points visited.
yList = []   # List of the y coordinates of all points visited.

while s <= NSteps:
    angle = radians(rand(361))
    x += cos(angle)    
    if x > N/2:
        x -= N
    elif x < -N/2:
        x += N    
    xList += [x]
    y += sin(angle)
    if y > N/2:
        y -= N
    elif y < -N/2:
        y += N
    yList += [y]    
    s += 1

plt.figure(figsize=(13,8))
frame = plt.gca()
plt.plot(xList,yList,c="b")
plt.xlim(-N/2,N/2)
plt.ylim(-N/2,N/2)
frame.axes.get_xaxis().set_visible(False)
frame.axes.get_yaxis().set_visible(False)
plt.savefig("randomWalk.png", bbox_inches="tight")

此代码生成如下图:

如您所见,每当粒子穿过其中一侧时,我都会在图上看到这些“条纹”,因为plot() 将连接两个点,无论它们相距多远。有没有办法防止这种情况发生?

【问题讨论】:

  • 我猜你可能不得不手动完成(例如,分割连续的步行部分并分别绘制它们) - 绘图代码无法知道不连续性在哪里。跨度>
  • 您也可以将np.nan 扔到您执行环绕代码的两个系列中。

标签: python python-3.x matplotlib


【解决方案1】:

我还稍微重写了您的步进代码,以使其更容易(在我看来)阅读:

from random import randrange as rand
from numpy import cos, sin, radians
import numpy as np
import matplotlib.pyplot as plt

N = 100   # Size of square as a multiple of the step size.
NSteps = 5000   # Number of steps in simulation.
xStart = 0   # x coordinate of starting location. Origin is at centre of square
yStart = 0   # y coordinate of starting location. Origin is at centre of square

s = 1   # Step number.
x = xStart   # x coordinate of point.
y = yStart   # y coordinate of point.
xList = []   # List of the x coordinates of all points visited.
yList = []   # List of the y coordinates of all points visited.

def wrap(v, N):

    if v > N/2:
        return v - N, True
    elif v < -N/2:
        return v + N, True
    return v, False


for j in range(NSteps):
    angle = radians(rand(361))
    x, wrap_flag_x = wrap(x + cos(angle), N)
    y, wrap_flag_y = wrap(y + sin(angle), N)
    if wrap_flag_x or wrap_flag_y:
        xList.append(np.nan)
        yList.append(np.nan)
    xList.append(x)
    yList.append(y)    

fig, ax = plt.subplots()
ax.plot(xList,yList,c="b")
ax.set_xlim(-N/2,N/2)
ax.set_ylim(-N/2,N/2)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)

他们正在输入np.nan(不是数字,它是浮点数的一部分 规格)到您的列表中。当 mpl 绘制线时,它(使用默认线型)连接所有点。无法将np.nan 的点绘制到屏幕上,因此不会绘制从最后一个点到np.nan 点的线,也不会绘制从np.nan 到下一个点的线,因此中断在你的行中。

附带说明,该模拟的大部分内容都可以矢量化:

from numpy.random import randint
from numpy import cos, sin, radians, cumsum
import numpy as np
import matplotlib.pyplot as plt

N = 100   # Size of square as a multiple of the step size.
NSteps = 5000   # Number of steps in simulation.
x_start = 0   # x coordinate of starting location. Origin is at centre of square
y_start = 0   # y coordinate of starting location. Origin is at centre of square



# get all of the angles
angles = radians(randint(low=0, high=361, size=NSteps))

# get (unwrapped) positions
x = cumsum(cos(angles)) + x_start
y = cumsum(sin(angles)) + y_start

# find where the position crosses the boundary
x_wraps = np.where(np.diff((x + N/2) // N))[0]
y_wraps = np.where(np.diff((y + N/2) // N))[0]

# do the wrapping
x = x - N * ((x + N/2)//N)
y = y - N * ((y + N/2)//N)

我离开使用包装位置插入 nans 作为读者的练习;)

【讨论】:

  • 感谢您的精彩回答,但不幸的是我不明白它是如何工作的! xList.append(np.nan)yList.append(np.nan) 到底在做什么?
猜你喜欢
  • 1970-01-01
  • 2015-06-16
  • 1970-01-01
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多