Step-by-Step Guide to Time Series Visualization Using Plotnine

6 graphics to explore your time series

7 min read

10 hours ago

Photo by Alex Litvin on Unsplash

Visualization is a quick and effective way of getting insights from your data. This article provides a step-by-step guide for exploring a time series using graphics.

We’ll use 6 different plots to uncover different aspects of a time series. We’ll focus on Python’s plotnine, a grammar-of-graphics type of library.

Introduction

Exploratory data analysis is an approach that aims to reveal the underlying structure of data sets. Almost always, this process involves using graphical techniques to visualize the data.

Using graphics for time series analysis is a quick way of extracting insights from the data, such as:

  • uncovering basic patterns, such as trends or seasonality
  • detecting irregularities, including missing data or outliers
  • detecting shifts in the distribution

In the rest of this article, you’ll learn how to build 6 graphics to explore a time series.

Exploring a Time Series

Let’s start by loading a time series. In this guide, we’ll use a monthly time series that is available in the M3 dataset [2]. We get it from the datasetsforecast library:

from datasetsforecast.m3 import M3

dataset, *_ = M3.load('./data', 'Monthly')

series = dataset.query(f'unique_id=="M400"')

You’ll learn how to create graphics using plotnine. This library is a sort of ggplot2 for Python. Let’s start by setting the theme :

import plotnine as p9

MY_THEME = p9.theme_538(base_family='Palatino', base_size=12) +
p9.theme(plot_margin=.025,
axis_text_y=p9.element_text(size=10),
panel_background=p9.element_rect(fill='white'),
plot_background=p9.element_rect(fill='white'),
strip_background=p9.element_rect(fill='white'),
legend_background=p9.element_rect(fill='white'),
axis_text_x=p9.element_text(size=10))

We’ll use a theme based on 538 with a few extra modifications.