matplotlib 时序图时间坐标显示
时间: 2023-09-16 21:11:35 浏览: 82
要在matplotlib的时序图中显示时间坐标,可以使用matplotlib内置的date模块。具体步骤如下:
1. 导入必要的库和模块:
```python
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY
import pandas as pd
from datetime import datetime
```
2. 准备数据,将时间列设置为pandas的DateTime类型:
```python
data = pd.read_csv('data.csv')
data['date'] = pd.to_datetime(data['date'])
```
3. 创建一个Figure对象和一个Axes对象:
```python
fig, ax = plt.subplots()
```
4. 设置日期格式化器和定位器:
```python
# 设置日期格式化器
date_format = DateFormatter('%Y-%m-%d')
# 设置周定位器和日定位器
mondays = WeekdayLocator(MONDAY)
days = DayLocator()
# 设置坐标轴格式
ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_minor_locator(days)
ax.xaxis.set_major_formatter(date_format)
```
5. 绘制时序图:
```python
ax.plot(data['date'], data['value'])
```
完整示例代码:
```python
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY
import pandas as pd
from datetime import datetime
# 准备数据
data = pd.read_csv('data.csv')
data['date'] = pd.to_datetime(data['date'])
# 创建Figure和Axes对象
fig, ax = plt.subplots()
# 设置日期格式化器
date_format = DateFormatter('%Y-%m-%d')
# 设置周定位器和日定位器
mondays = WeekdayLocator(MONDAY)
days = DayLocator()
# 设置坐标轴格式
ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_minor_locator(days)
ax.xaxis.set_major_formatter(date_format)
# 绘制时序图
ax.plot(data['date'], data['value'])
# 显示图形
plt.show()
```
阅读全文