找到距 (0,0) 的最大距离并添加到图例 matplotlib

Find max distance from (0,0) and add to legend matplotlib

我有这段代码计算随机游走,我试图找到所有游走距 (0.0) 的最大距离并将它们添加到图例中。添加了我想要实现的结果的图像。

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

np.random.seed(12)
repeats = 5 
N_steps = 1000000
expected_R = np.sqrt(N_steps)

plt.title(f"{repeats} random walks of {N_steps} steps")

for x in range(repeats):
    dirs = np.random.randint(0, 4, N_steps)
    steps = np.empty((N_steps, 2))

    steps[dirs == 0] = [0, 1]  # 0 - right
    steps[dirs == 1] = [0, -1]  # 1 - left
    steps[dirs == 2] = [1, 0]  # 2 - up
    steps[dirs == 3] = [-1, 0]  # 3 - down
        
    steps = steps.cumsum(axis=0)

    print("Final position:", steps[-1])

    skip = N_steps // 5000 + 1
    xs = steps[::skip, 0]
    ys = steps[::skip, 1]

    x = max(ys)

    plt.plot(xs, ys)
    

circle = plt.Circle((0, 0), radius=expected_R, color="k")
plt.gcf().gca().add_artist(circle)
plt.gcf().gca().set_aspect("equal")
plt.axis([-1500-x,1500+x,-1500-x,1500+x])

plt.show()

您可以使用 distance=np.linalg.norm(steps, axis=1) 绘制从坐标 steps0,0 的距离。然后你可以取这个数组的最大值来找到最大距离。然后,您可以为绘图和图例添加标签。 请参阅下面的代码:

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

np.random.seed(12)
repeats = 5 
N_steps = 1000000
expected_R = np.sqrt(N_steps)

plt.title(f"{repeats} random walks of {N_steps} steps")
max_distance=np.zeros(repeats)
for x in range(repeats):
    dirs = np.random.randint(0, 4, N_steps)
    steps = np.empty((N_steps, 2))

    steps[dirs == 0] = [0, 1]  # 0 - right
    steps[dirs == 1] = [0, -1]  # 1 - left
    steps[dirs == 2] = [1, 0]  # 2 - up
    steps[dirs == 3] = [-1, 0]  # 3 - down
        
    steps = steps.cumsum(axis=0)

    print("Final position:", steps[-1])

    skip = N_steps // 5000 + 1
    xs = steps[::skip, 0]
    ys = steps[::skip, 1]
    distance=np.linalg.norm(steps, axis=1)
    max_distance[x]=np.amax(distance)
    plt.plot(xs, ys,label='Random walk '+str(x)+': max distance: '+str(np.round(max_distance[x],1)))
    

circle = plt.Circle((0, 0), radius=expected_R, color="k")
plt.gcf().gca().add_artist(circle)
plt.gcf().gca().set_aspect("equal")
plt.axis([-1500-x,1500+x,-1500-x,1500+x])
plt.legend(fontsize=8)
plt.show()

并且输出给出: