使用 Matplotlib 创建事件图

Beginner

This tutorial is from open-source community. Access the source code

简介

在本实验中,你将学习如何使用 Matplotlib 创建事件图。事件图是一种展示事件随时间发生情况的方式。事件可以用线条或点来表示。本实验将指导你创建具有不同线条属性的水平和垂直事件图。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签页,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会及时为你解决问题。

导入库并设置随机种子

我们将首先导入必要的库,并设置一个随机种子以确保可重复性。

import matplotlib.pyplot as plt
import numpy as np

import matplotlib

matplotlib.rcParams['font.size'] = 8.0

## Fixing random state for reproducibility
np.random.seed(19680801)

创建随机数据

接下来,我们将创建一些随机数据用于我们的事件图。

data1 = np.random.random([6, 50])

为第一个事件图设置颜色和线条属性

我们将为第一个事件图中的每组位置设置不同的颜色和线条属性。

colors1 = [f'C{i}' for i in range(6)]

lineoffsets1 = [-15, -3, 1, 1.5, 6, 10]
linelengths1 = [5, 2, 1, 1, 3, 1.5]

创建第一个事件图 - 水平方向

我们将创建第一个水平方向的事件图。

fig, axs = plt.subplots(2, 2)

axs[0, 0].eventplot(data1, colors=colors1, lineoffsets=lineoffsets1,
                    linelengths=linelengths1)

创建第一个事件图 - 垂直方向

我们将创建第一个垂直方向的事件图。

axs[1, 0].eventplot(data1, colors=colors1, lineoffsets=lineoffsets1,
                    linelengths=linelengths1, orientation='vertical')

为第二个事件图创建随机数据

我们将为第二个事件图创建另一组随机数据。出于美观目的,我们将使用伽马分布。

data2 = np.random.gamma(4, size=[60, 50])

为第二个事件图设置线条属性

我们将在第二个事件图中为线条属性使用单独的值。这些值将用于所有数据集,但 lineoffsets2 除外,它设置每个数据集之间的增量。

colors2 = 'black'
lineoffsets2 = 1
linelengths2 = 1

创建第二个事件图 - 水平方向

我们将创建第二个水平方向的事件图。

axs[0, 1].eventplot(data2, colors=colors2, lineoffsets=lineoffsets2,
                    linelengths=linelengths2)

创建第二个事件图 - 垂直方向

我们将创建第二个垂直方向的事件图。

axs[1, 1].eventplot(data2, colors=colors2, lineoffsets=lineoffsets2,
                    linelengths=linelengths2, orientation='vertical')

显示事件图

我们将使用 plt.show() 来显示事件图。

plt.show()

总结

在本实验中,你学习了如何在 Matplotlib 中创建事件图。你学习了如何使用不同的线条属性创建水平和垂直的事件图。按照逐步指南,你可以轻松地为自己的数据创建事件图。