Mathew K Analytics

Lesson 38 · Data visualisation in python

Time Series Visualization Techniques Using Matplotlib and Plotly in Python

Welcome! Today you will learn to graph time-based data using Python. You will use Matplotlib and Plotly for awesome, interactive plots! By the end, you will…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Time Series Visualization in Python: A Beginner's Guide#

Welcome! Today you will learn to graph time-based data using Python.

You will use Matplotlib and Plotly for awesome, interactive plots!

By the end, you will build real time series charts and impress yourself.

import warnings
warnings.filterwarnings("ignore")
# Import core modules
import pandas as pd
import matplotlib.pyplot as plt
import plotly.express as px
 
 

Why plot time series?#

Time series are data measured over timelike weather, sales, or website visitors. Plots help you see patterns, trends, and surprises you might miss in a table.

# Data setup
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv"
df = pd.read_csv(url)
print("Shape:", df.shape)
df.head()
Shape: (144, 2)
Month Passengers
0 1949-01 112
1 1949-02 118
2 1949-03 132
3 1949-04 129
4 1949-05 121
# Convert Month string to datetime, check types
df['Month'] = pd.to_datetime(df['Month'])
print(df.dtypes)
Month         datetime64[ns]
Passengers             int64
dtype: object

Let us make your first time series plot!#

Line graphs are perfect for time series. The line helps you see changes over months. You will use Matplotlib first.

# Simple line plot of passengers over time
plt.figure(figsize=(10,5))
plt.plot(df['Month'], df['Passengers'], marker='.')
plt.title('Monthly Airline Passengers')
plt.xlabel('Month')
plt.ylabel('Number of Passengers')
plt.grid(True)
plt.show()
No description has been provided for this image
# Interactive plotly line plot
fig = px.line(df, x='Month', y='Passengers', title='Monthly Airline Passengers (Interactive)')
fig.show()

Making sense of trends and seasonality#

Trends are long, steady movement up or down. Seasonality is a repeating pattern every year, month, or week. Your airline chart has botha rising trend and yearly cycles.

# Let us highlight the trend with a rolling mean
df['MA12'] = df['Passengers'].rolling(window=12).mean()
plt.figure(figsize=(10,5))
plt.plot(df['Month'], df['Passengers'], alpha=0.5, label='Passengers')
plt.plot(df['Month'], df['MA12'], color='red', label='12-Month Average')
plt.legend()
plt.title('Passengers and 12-Month Trend')
plt.show()
No description has been provided for this image
# Handling missing data safely
print('Any missing? ', df.isnull().values.any())
df2 = df.copy()
df2.loc[5, 'Passengers'] = None  # Simulate a missing value
print('Any missing now?', df2.isnull().values.any())
df2['Passengers'].fillna(method='ffill', inplace=True)
print('Missing after fill:', df2['Passengers'].isnull().sum())
Any missing?  True
Any missing now? True
Missing after fill: 0
# Zoom in on a single year
mask = (df['Month'] >= '1957-01-01') & (df['Month'] < '1958-01-01')
df_1957 = df[mask]
plt.figure(figsize=(8,4))
plt.plot(df_1957['Month'], df_1957['Passengers'], marker='o')
plt.title('Passengers in 1957')
plt.xlabel('Month')
plt.ylabel('Passengers')
plt.show()
No description has been provided for this image
# Multiple lines: compare different years
for yr in [1956, 1957, 1958]:
    mask = (df['Month'].dt.year == yr)
    plt.plot(df.loc[mask, 'Month'].dt.month, df.loc[mask, 'Passengers'], label=str(yr))
plt.title('Compare 1956, 1957, and 1958')
plt.xlabel('Month')
plt.ylabel('Passengers')
plt.legend()
plt.show()
No description has been provided for this image
# Add customizations: color, style, labels
plt.figure(figsize=(10,5))
plt.plot(df['Month'], df['Passengers'], 'g--', label='Passengers')
plt.title('Styled Time Series Plot')
plt.xlabel('Time')
plt.ylabel('People Flying')
plt.legend()
plt.show()
No description has been provided for this image
# Plotly: add range slider and buttons
fig = px.line(df, x='Month', y='Passengers', title='Passengers with Range Slider')
fig.update_layout(xaxis_rangeslider_visible=True,
                  updatemenus=[
                      dict(type='buttons',
                           showactive=False,
                           buttons=[
                               dict(label='Linear',
                                    method='relayout',
                                    args=[{'yaxis.type': 'linear'}]),
                               dict(label='Log',
                                    method='relayout',
                                    args=[{'yaxis.type': 'log'}])
                           ])
                  ])
fig.show()

Cool tricks: highlighting and annotation#

You can make key points stand out. Try annotating an unusual jump or drop in your data for extra insight.

# Annotate an extreme point
mx_idx = df['Passengers'].idxmax()
mx_month = df.loc[mx_idx, 'Month']
mx_val = df.loc[mx_idx, 'Passengers']
plt.figure(figsize=(10,5))
plt.plot(df['Month'], df['Passengers'])
plt.scatter([mx_month], [mx_val], color='red', zorder=5)
plt.annotate('Peak Passengers', (mx_month, mx_val), xytext=(mx_month, mx_val+50),
             arrowprops={'arrowstyle':'->', 'color':'red'})
plt.title('Annotate Highest Point')
plt.show()
No description has been provided for this image
# Save a plot to file for reports
plt.figure(figsize=(10,5))
plt.plot(df['Month'], df['Passengers'])
plt.title('Report Example')
plt.savefig('report_plot.png')
plt.close()

Challenge: try a new dataset#

Visit https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv and load it with pandas. Create a simple time series line plot of temperatures over days. Use the steps you learned above.

Summary: what have you learned?#

  • How to load time series data
  • How to plot with Matplotlib and Plotly
  • Tricks like smoothing, focusing, annotating, and saving
  • Tips for handling missing data and comparing years

Keep practicing on different datasets to build your skills!

Subscribe for more Python tips!#

If this was helpful, like and subscribe for more tutorials on Python and data science. Comment your favorite dataset to plot next!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.