Série temporelle avec matplotlib

Active 14 juin 2014    /    Viewed 4763    /    Comments 0    /    Edit

Pour tracer une série temporelle avec matplotlib, le plus simple est de passer par pandas. Exemple simple:

Série temporelle avec matplotlib et Pandas

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

ts = pd.Series(np.random.randn(1000), \
               index=pd.date_range('1/1/2000', \
ts = ts.cumsum()


Exemple de série temporelle avec matplotlib avec les labels orientés verticalement (source)

Série temporelle avec matplotlib (exemple 1)

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

a = np.array([
    [1293605162197, 500, 1000],
    [1293605477994, 200, 300],
    [1293605478057, 50, 150],
    [1293605478072, 2500, 2000],
    [1293606162213, 500, 1000],
    [1293606162229, 200, 600]])

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.set_ylim(bottom = 0)


Encore un autre exemple de série temporelle avec matplotlib (source)

Série temporelle avec matplotlib (exemple 2)

from matplotlib.dates import WeekdayLocator

def plot_series(x, y):
    fig, ax = plt.subplots()
    ax.plot_date(x, y, fmt='g--') # x = array of dates, y = array of numbers


    # For tickmarks and ticklabels every fourth week
    ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MO, interval=4))

    # For tickmarks (no ticklabel) every week

    # Grid for both major and minor ticks
    plt.grid(True, which='both')

Recherches associées

Liens Site
Plotting with matplotlib & pandas Pandas doc
Creating graph with date and time in axis labels with matplotlib stackoverflow
Matthias Friedrich's Blog blog
How to plot time series in python stackoverflow
Ways to reduce high dimensional data for visualization stackexchange
Série temporelle Wikipedia Wikipedia
numpy.random.randn Scipy Doc
Cookbook / FittingData Scipy Doc
Custom date range (x-axis) in time series with matplotlib stackoverflow

Card image cap

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!