简体   繁体   中英

Plotting chart with epoch time x axis using matplotlib

I have the following code to plot a chart with 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).

How can I do that?

To plot date-based data in matplotlib you must convert the data to the correct format.

One way is to first convert your data to datetime objects, for an epoch timestamp you should use datetime.datetime.fromtimestamp() .

You must then convert the datetime objects to the right format for matplotlib, this can be handled using 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).

Once you have your data in the correct format you can plot it using 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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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