使用matplotlib在轴标签中创建带有日期和时间的图形 [英] Creating graph with date and time in axis labels with matplotlib

查看:118
本文介绍了使用matplotlib在轴标签中创建带有日期和时间的图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将数据存储在以下结构的数组中

I have my data in an array of the following structure,

[[1293606162197, 0, 0],
 [1293605477994, 63, 0],
 [1293605478057, 0, 0],
 [1293605478072, 2735, 1249],
 [1293606162213, 0, 0],
 [1293606162229, 0, 0]]

第一列是纪元时间(在ms中),第二列是y1,第三列是y2.我需要一个在x轴上有时间的图,在左和右y轴上分别是y1y2.

The first column is epoch time (in ms), second is y1 and third is y2. I need a plot with the time on the x-axis, and y1 and y2 on left and right y-axes.

我一直在仔细阅读文档,但是找不到任何使我的x轴刻度显示日期和时间的方法,例如"28/12 16:48",即"date/month hour:min ".所有文档对我有帮助的是仅显示日期,但这不是我想要的.任何帮助将不胜感激.

I have been scouring through the documentation but couldn't find any way to get my x-axis ticks to display both date and time, like "28/12 16:48", i.e., "date/month hour:min". All the documentation helps me with is to display dates alone, but that is not what I want. Any help would be appreciated on this.

而且,如果看起来像这样,那不是功课.实际上,这是我上一个问题的后续操作,读取并绘制数据图形从大文件中.

And, if it may seem like, this is not homework. It is actually a follow up to my previous question, Reading and graphing data read from huge files.

推荐答案

我希望这会有所帮助.我一直很难过matplotlib的约会. Matplotlib需要一种浮动格式,距时代已经过去了几天.辅助函数num2datedate2num以及python内置的datetime可用于转换.格式化业务从示例中删除.您可以使用set_major_formatter将任何绘图上的轴更改为日期轴.

I hope this helps. I've always had a hard time with matplotlib's dates. Matplotlib requires a float format which is days since epoch. The helper functions num2date and date2num along with python builtin datetime can be used to convert to/from. The formatting business was lifted from this example. You can change an axis on any plot to a date axis using set_major_formatter.

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import dates
import datetime

a = np.array([
    [1293605162197, 0, 0],
    [1293605477994, 63, 0],
    [1293605478057, 0, 0],
    [1293605478072, 2735, 1249],
    [1293606162213, 0, 0],
    [1293606162229, 0, 0]])

d = a[:,0]
y1 = a[:,1]
y2 = a[:,2]

# convert epoch to matplotlib float format
s = d/1000
ms = d-1000*s  # not needed?
dts = map(datetime.datetime.fromtimestamp, s)
fds = dates.date2num(dts) # converted

# matplotlib date format object
hfmt = dates.DateFormatter('%m/%d %H:%M')

fig = plt.figure()
ax = fig.add_subplot(111)
ax.vlines(fds, y2, y1)

ax.xaxis.set_major_locator(dates.MinuteLocator())
ax.xaxis.set_major_formatter(hfmt)
ax.set_ylim(bottom = 0)
plt.xticks(rotation='vertical')
plt.subplots_adjust(bottom=.3)
plt.show()

这篇关于使用matplotlib在轴标签中创建带有日期和时间的图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆