【python】pyplot绘制横轴为时间的图

1. 导入环境

import numpy as np
import matplotlib.pyplot as plt

from IPython import display
from datetime import datetime
from datetime import date

2. 绘图方法


def myplot(x, y, label=None, xlimit=None, size=(9, 3),fileName=None):
    display.set_matplotlib_formats('svg')
    if len(x) == len(y):
        plt.figure(figsize=size)
        if xlimit and isinstance(xlimit, tuple):
            plt.xlim(xlimit)
        plt.plot(x, y, label=label)
        if label and isinstance(label, str):
            plt.legend()
        if fileName:
            plt.savefig(fileName)
        plt.show()
    else:
        raise ValueError("x 和 y 的长度不一致!")

3. 绘图

原始横坐标数组是一个字符串型的,无法直接用于plot(x, y)中的x


time[0:10]
array([['2019-01-01 00:14:00'],
       ['2019-01-01 00:29:00'],
       ['2019-01-01 00:44:00'],
       ['2019-01-01 00:59:00'],
       ['2019-01-01 01:14:00'],
       ['2019-01-01 01:29:00'],
       ['2019-01-01 01:44:00'],
       ['2019-01-01 01:59:00'],
       ['2019-01-01 02:14:00'],
       ['2019-01-01 02:29:00']], dtype='<U19')

将字符串的时间转换成date对象

x_time= [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in time]  

绘图

myplot(x_time, y_num, label='car_num', 
       xlimit=(date(2019, 1, 1), date(2019, 1, 22) ),
       size=(12, 3),
       fileName='my_dataset-car-num.svg')

在这里插入图片描述

4.自定义x轴日期显示格式

如果想自定义坐标轴显示格式,可以更改一下绘图方法,通过DateFormatter来实现。

from matplotlib.dates import DateFormatter

def myplot(x, y, label=None, xlimit=None, size=(9, 3),fileName=None):
    display.set_matplotlib_formats('svg')
    if len(x) == len(y):
        plt.figure(figsize=size)
        if xlimit and isinstance(xlimit, tuple):
            plt.xlim(xlimit)
        plt.plot(x, y, label=label)
        if label and isinstance(label, str):
            plt.legend()
        if fileName:
            plt.savefig(fileName)
        # ======= 以下是新增代码
        ax = plt.gca()
        formatter = DateFormatter('%H:%M')
        ax.xaxis.set_major_formatter(formatter) # 设置时间显示格式   
        # ==============
        plt.show()
    else:
        raise ValueError("x 和 y 的长度不一致!")

效果如下:
在这里插入图片描述

  • 13
    点赞
  • 92
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值