88.md 1.5 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
# 使用 matplotlib 绘制时间

> 原文: [https://pythonspot.com/plot-time-with-matplotlib/](https://pythonspot.com/plot-time-with-matplotlib/)

Matplotlib 支持在水平(x)轴上带有时间的图。 数据值将放在垂直(y)轴上。 在本文中,我们将通过一些示例进行演示。

需要使用 Python datetime 模块(标准模块)。

## 绘制时间

您可以使用时间戳绘制时间:

```py

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import datetime

# create data
y = [ 2,4,6,8,10,12,14,16,18,20 ]
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(len(y))]

# plot
plt.plot(x,y)
plt.gcf().autofmt_xdate()
plt.show()

```

W
wizardforcel 已提交
31
![matplotilb-time](img/35ae64518583e605bb57af58666ccecd.jpg)
W
init  
wizardforcel 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

如果要更改间隔,请使用以下几行之一:

```py

# minutes
x = [datetime.datetime.now() + datetime.timedelta(minutes=i) for i in range(len(y))]

```

## 从特定小时/分钟开始的时间图


要从特定日期开始,请使用 datetime.datetime(年,月,日,小时,分钟)创建新的时间戳。
完整示例:

```py

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import datetime

# create data
customdate = datetime.datetime(2016, 1, 1, 13, 30)
y = [ 2,4,6,8,10,12,14,16,18,20 ]
x = [customdate + datetime.timedelta(hours=i) for i in range(len(y))]

# plot
plt.plot(x,y)
plt.gcf().autofmt_xdate()
plt.show()

```

[下载示例](https://pythonspot.com/download-matplotlib-examples/)