简体   繁体   English

使用matplotlib绘制带有纪元时间x轴的图表

[英]Plotting chart with epoch time x axis using matplotlib

I have the following code to plot a chart with matplotlib 我有以下代码用matplotlib绘制图表

#!/usr/bin/env python
import matplotlib.pyplot as plt
import urllib2
import json

req = urllib2.urlopen("http://localhost:17668/retrieval/data/getData.json?        pv=LNLS:ANEL:corrente&donotchunk")
data = json.load(req)
secs = [x['secs'] for x in data[0]['data']]
vals = [x['val'] for x in data[0]['data']]

plt.plot(secs, vals)
plt.show()

The secs arrays is epoch time. 秒数组是纪元时间。

What I want is to plot the data in the x axis (secs) as a date (DD-MM-YYYY HH:MM:SS). 我想要的是将x轴(秒)中的数据绘制为日期(DD-MM-YYYY HH:MM:SS)。

How can I do that? 我怎样才能做到这一点?

To plot date-based data in matplotlib you must convert the data to the correct format. 要在matplotlib中绘制基于日期的数据,您必须将数据转换为正确的格式。

One way is to first convert your data to datetime objects, for an epoch timestamp you should use datetime.datetime.fromtimestamp() . 一种方法是首先将数据转换为datetime对象,对于epoch时间戳,您应该使用datetime.datetime.fromtimestamp()

You must then convert the datetime objects to the right format for matplotlib, this can be handled using matplotlib.date.date2num . 然后必须将datetime对象转换为matplotlib的正确格式,这可以使用matplotlib.date.date2num来处理。

Alternatively you can use matplotlib.dates.epoch2num and skip converting your date to datetime objects in the first place (while this will suit your use-case better initially, I would recommend trying to keep date based date in datetime objects as much as you can when working, it will save you a headache in the long run). 或者您可以使用matplotlib.dates.epoch2num并首先跳过将日期转换为datetime对象(虽然这最初会更好地适合您的用例,但我建议您尽可能多地在datetime对象中保留基于日期的datetime工作时,从长远来看会让你头疼不已)。

Once you have your data in the correct format you can plot it using plot_date . 一旦您的数据格式正确,您可以使用plot_date绘制它。

Finally to format your x-axis as you wish you can use a matplotlib.dates.DateFormatter object to choose how your ticks will look. 最后根据需要格式化您的x轴,您可以使用matplotlib.dates.DateFormatter对象来选择刻度的外观。

import matplotlib.pyplot as plt
import matplotlib.dates as mdate

import numpy as np

# Generate some random data.
N = 40
now = 1398432160
raw = np.array([now + i*1000 for i in range(N)])
vals = np.sin(np.linspace(0,10,N))

# Convert to the correct format for matplotlib.
# mdate.epoch2num converts epoch timestamps to the right format for matplotlib
secs = mdate.epoch2num(raw)


fig, ax = plt.subplots()

# Plot the date using plot_date rather than plot
ax.plot_date(secs, vals)

# Choose your xtick format string
date_fmt = '%d-%m-%y %H:%M:%S'

# Use a DateFormatter to set the data to the correct format.
date_formatter = mdate.DateFormatter(date_fmt)
ax.xaxis.set_major_formatter(date_formatter)

# Sets the tick labels diagonal so they fit easier.
fig.autofmt_xdate()

plt.show()

情节

You can change the ticks locations and formats on your plot: 您可以更改地块上的刻度线位置和格式:

import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import time

secs = [10928389,102928123,383827312,1238248395]
vals = [12,8,4,12]

plt.plot(secs,vals)

plt.gcf().autofmt_xdate()

plt.gca().xaxis.set_major_locator(mtick.FixedLocator(secs))
plt.gca().xaxis.set_major_formatter(
    mtick.FuncFormatter(lambda pos,_: time.strftime("%d-%m-%Y %H:%M:%S",time.localtime(pos)))
    )
plt.tight_layout()
plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM