简介
在本实验中,我们将学习如何使用 Python 中的 Matplotlib 创建带有数据点的折线图。我们将使用 Matplotlib 中的 EventCollection 类在每条曲线的相应轴上标记 x 和 y 数据点的位置。
虚拟机使用提示
虚拟机启动完成后,点击左上角切换到 笔记本 标签页,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,请随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。
导入必要的库
首先,我们需要导入所需的库。我们将使用 numpy 创建随机数据,使用 matplotlib.pyplot 创建图表,并使用 matplotlib.collections 中的 EventCollection 来标记数据点的位置。
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import EventCollection
创建随机数据
我们将使用 numpy.random.random() 函数为两条曲线创建随机数据。我们将生成两组介于 0 和 1 之间的 10 个随机数,并将它们存储在一个数组中。
## create random data
xdata = np.random.random([2, 10])
对数据进行排序
为了绘制出平滑的曲线,我们将使用 sort() 方法对数据进行排序。
## split the data into two parts
xdata1 = xdata[0, :]
xdata2 = xdata[1, :]
## sort the data so it makes clean curves
xdata1.sort()
xdata2.sort()
创建 y 数据点
我们将通过对已排序的 x 数据点进行一些数学运算,为每条曲线创建一些 y 数据点。
## create some y data points
ydata1 = xdata1 ** 2
ydata2 = 1 - xdata2 ** 3
创建图表
我们将使用 matplotlib.pyplot.plot() 函数来创建图表。
## plot the data
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(xdata1, ydata1, color='tab:blue')
ax.plot(xdata2, ydata2, color='tab:orange')
创建事件
我们将使用 EventCollection() 函数来创建标记 x 和 y 数据点的事件。
## create the events marking the x data points
xevents1 = EventCollection(xdata1, color='tab:blue', linelength=0.05)
xevents2 = EventCollection(xdata2, color='tab:orange', linelength=0.05)
## create the events marking the y data points
yevents1 = EventCollection(ydata1, color='tab:blue', linelength=0.05,
orientation='vertical')
yevents2 = EventCollection(ydata2, color='tab:orange', linelength=0.05,
orientation='vertical')
将事件添加到图表中
我们将使用 matplotlib.pyplot.add_collection() 函数把这些事件添加到图表中。
## add the events to the axis
ax.add_collection(xevents1)
ax.add_collection(xevents2)
ax.add_collection(yevents1)
ax.add_collection(yevents2)
设置坐标轴范围并添加标题
我们将使用 matplotlib.pyplot.xlim()、matplotlib.pyplot.ylim() 和 matplotlib.pyplot.title() 函数来设置 x 轴和 y 轴的范围,并为图表添加标题。
## set the limits
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
ax.set_title('line plot with data points')
显示图表
最后,我们将使用 matplotlib.pyplot.show() 函数来显示图表。
## display the plot
plt.show()
总结
在本实验中,我们学习了如何使用 Python 中的 Matplotlib 创建带有数据点的折线图。我们使用了 Matplotlib 中的 EventCollection 类来标记每条曲线在各自坐标轴上 x 和 y 数据点的位置。