在Matplotlib中绘制Python日期时间的累积图
Matplotlib是Python中最流行的可视化库之一,可以使用它绘制各种类型的图表。在本文中,我们将学习如何使用Matplotlib绘制Python日期时间的累积图。累积图(Cumulative Chart)可以用于显示某个数据随时间变化的总体趋势。
我们将使用Python中的datetime模块来处理日期和时间。首先,我们需要导入必要的库。代码如下所示:
import matplotlib.pyplot as plt
import datetime as dt
import numpy as np
下面是一些生成示例数据的代码,我们将生成一个包含10个日期时间和相应值的列表。代码如下所示:
times = [dt.datetime(2021, 1, 1, 0, 0, 0)]
values = [0]
for i in range(1, 10):
times.append(dt.datetime(2021, 1, 1+i, 0, 0, 0))
values.append(np.random.randint(1, 10))
这里我们将列表times
的第一个元素设置为2021 年1 月1 日。用于生成值的numpy
的random.randint()
函数将从1到10范围内随机选择一个整数。接下来,我们将使用Matplotlib绘制累积图。代码如下所示:
# 绘制累积图
fig, ax = plt.subplots()
ax.plot(times, np.cumsum(values))
ax.set(xlabel='时间', ylabel='值', title='累积图')
fig.autofmt_xdate()
plt.show()
在这个代码中,我们使用了Matplotlib的子图(subplots) 函数和曲线函数,指定了x轴和y轴的标签,以及标题。fig.autofmt_xdate()
函数调整x轴标签的方向。
运行上面的代码,就可以得到一个累积图。以下是完整的代码示例:
import matplotlib.pyplot as plt
import datetime as dt
import numpy as np
times = [dt.datetime(2021, 1, 1, 0, 0, 0)]
values = [0]
for i in range(1, 10):
times.append(dt.datetime(2021, 1, 1+i, 0, 0, 0))
values.append(np.random.randint(1, 10))
# 绘制累积图
fig, ax = plt.subplots()
ax.plot(times, np.cumsum(values))
ax.set(xlabel='时间', ylabel='值', title='累积图')
fig.autofmt_xdate()
plt.show()
结论
本文介绍了如何在Matplotlib中绘制Python日期时间的累积图。在这个例子中,我们通过使用datetime模块创建日期和时间值的列表,然后使用Matplotlib的plot函数绘制累积图。这个例子是一个简单的例子,演示了如何创建累积图。你可以根据你自己的需求调整时间间隔和数据点,为你的数据集创建和定制累积图。