可视化这次行走
让我们把这次随机游走可视化!还记得如何用 matplotlib 绘制折线图吗?
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.show()
传入的第一个列表会映射到 x 轴,第二个列表会映射到 y 轴。
如果只传入一个参数,Python 会自动处理:使用该列表的索引映射到 x 轴,列表中的值映射到 y 轴。
本练习是课程的一部分
Python 中级
练习说明
在 for 循环之后添加几行代码:
- 将
matplotlib.pyplot以plt的别名导入。 - 使用
plt.plot()绘制random_walk。 - 最后调用
plt.show()实际显示图形。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# NumPy is imported, seed is set
# Initialization
random_walk = [0]
for x in range(100) :
step = random_walk[-1]
dice = np.random.randint(1,7)
if dice <= 2:
step = max(0, step - 1)
elif dice <= 5:
step = step + 1
else:
step = step + np.random.randint(1,7)
random_walk.append(step)
# Import matplotlib.pyplot as plt
# Plot random_walk
# Show the plot