python使用pyplot绘制横轴为时间的图
更新时间:2024年09月19日 09:32:49 作者:豆腐脑lr
介绍了如何在Python中使用matplotlib库进行绘图,并处理字符串日期格式转换为date对象以及自定义x轴日期显示格式的方法,首先,导入必要的环境和绘图方法,其次,处理横坐标数组,将字符串型的日期转换成date对象,以便用于绘图
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 的长度不一致!")效果如下:

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Python TensorFlow 2.6获取MNIST数据的示例代码
这篇文章主要介绍了Python TensorFlow 2.6获取MNIST数据的的相关示例,文中有详细的代码示例供大家参考,对大家的学习或工作有一定的帮助,需要的朋友可以参考下2024-04-04
Pycharm安装第三方库时Non-zero exit code错误解决办法
这篇文章主要介绍了Pycharm安装第三方库时Non-zero exit code错误解决办法,最好的解决办法可以通过“Pycharm”左下角的“Terminal”,在pycharm内使用pip安装,以安装“requests”为例,需要的朋友可以参考下2023-01-01
python3连接mysql获取ansible动态inventory脚本
Ansible Inventory 是包含静态 Inventory 和动态 Inventory 两部分的,静态 Inventory 指的是在文件中指定的主机和组,动态 Inventory 指通过外部脚本获取主机列表。这篇文章主要介绍了python3连接mysql获取ansible动态inventory脚本,需要的朋友可以参考下2020-01-01
python爬虫之利用Selenium+Requests爬取拉勾网
这篇文章主要介绍了python爬虫之利用Selenium+Requests爬取拉勾网,文中有非常详细的代码示例,对正在学习python爬虫的小伙伴们有很好的帮助,需要的朋友可以参考下2021-04-04


最新评论