在同一图上叠加多条曲线
西雅图市在弗里蒙特大桥两侧(东侧和西侧)安装了计数器,用于记录南北向车流中的自行车通行量。
在本练习中,您将使用 for 循环和 matplotlib,探索大桥东、西两侧在一天中交通量如何变化。了解早晚高峰期间两侧的使用情况,有助于未来建设与这条高通行路线相连接的自行车基础设施。
当您在编写 for 循环且需要记录当前位置时,Python 中一个很有用的函数是 enumerate()。
things = ['first thing', 'second', 'yet another']
for ii, item in enumerate(things):
print(ii, item)
0 first thing
1 second
2 yet another
本练习是课程的一部分
面向 MATLAB 用户的 Python
练习说明
- 查看数组
weekday_traffic的形状,分别识别哪一维对应大桥的侧别、哪一维对应一天中的小时。 - 使用
enumerate()计数,遍历weekday_traffic的列。 - 在每次循环中,绘制
weekday_traffic的该列数据,并使用sidewalk中对应的label进行标注。 - 创建图例并显示图表。
交互式实操练习
通过完成这段示例代码来试试这个练习。
sidewalk = ['East','West']
# Explore the shape of the array weekday_traffic
print(weekday_traffic.____)
# Loop over the columns of weekday_traffic, counting the number of iterations
for ii, sidewalk_traffic in ____(weekday_traffic.T):
# Plot the column with the corresponding label in sidewalk
plt.plot(sidewalk_traffic, ____=sidewalk[ii])
# Create the legend and show the plot
plt.____()
____