Matplotlib Date Tick Customization Using Recurrence Rules

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to use recurrence rules in Matplotlib to place date ticks. The iCalender RFC_ specifies recurrence rules (rrules), that define date sequences. You can use rrules in Matplotlib to place date ticks. This example sets custom date ticks on every 5th Easter.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/PythonStandardLibraryGroup -.-> python/date_time("`Date and Time`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48652{{"`Matplotlib Date Tick Customization Using Recurrence Rules`"}} matplotlib/figures_axes -.-> lab-48652{{"`Matplotlib Date Tick Customization Using Recurrence Rules`"}} matplotlib/line_plots -.-> lab-48652{{"`Matplotlib Date Tick Customization Using Recurrence Rules`"}} python/tuples -.-> lab-48652{{"`Matplotlib Date Tick Customization Using Recurrence Rules`"}} python/importing_modules -.-> lab-48652{{"`Matplotlib Date Tick Customization Using Recurrence Rules`"}} python/using_packages -.-> lab-48652{{"`Matplotlib Date Tick Customization Using Recurrence Rules`"}} python/standard_libraries -.-> lab-48652{{"`Matplotlib Date Tick Customization Using Recurrence Rules`"}} python/math_random -.-> lab-48652{{"`Matplotlib Date Tick Customization Using Recurrence Rules`"}} python/date_time -.-> lab-48652{{"`Matplotlib Date Tick Customization Using Recurrence Rules`"}} python/numerical_computing -.-> lab-48652{{"`Matplotlib Date Tick Customization Using Recurrence Rules`"}} python/data_visualization -.-> lab-48652{{"`Matplotlib Date Tick Customization Using Recurrence Rules`"}} python/build_in_functions -.-> lab-48652{{"`Matplotlib Date Tick Customization Using Recurrence Rules`"}} end

Import the necessary libraries

First, you need to import the necessary libraries, including Matplotlib, NumPy, and datetime.

import datetime
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.dates import (YEARLY, DateFormatter, RRuleLocator, drange,
                              rrulewrapper)

Set the random seed

You will be generating random data for this example, so you need to set the random seed for reproducibility.

np.random.seed(19680801)

Set the recurrence rule

You will be setting custom date ticks on every 5th Easter. To do this, you need to set the recurrence rule using the rrulewrapper function.

rule = rrulewrapper(YEARLY, byeaster=1, interval=5)

Set the tick locator and formatter

You will use the RRuleLocator function to set the tick locator based on the recurrence rule you set in the previous step. You will also use the DateFormatter function to set the tick formatter.

loc = RRuleLocator(rule)
formatter = DateFormatter('%m/%d/%y')

Set the dates and generate random data

You need to set the start and end dates and the delta, which represents the difference between each date. You also need to generate random data for the example.

date1 = datetime.date(1952, 1, 1)
date2 = datetime.date(2004, 4, 12)
delta = datetime.timedelta(days=100)

dates = drange(date1, date2, delta)
s = np.random.rand(len(dates))

Plot the data and set the x-axis ticks

Finally, you can plot the data using the plot function, and set the x-axis ticks using the tick locator and formatter functions you set earlier.

fig, ax = plt.subplots()
plt.plot(dates, s, 'o')
ax.xaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(formatter)
ax.xaxis.set_tick_params(rotation=30, labelsize=10)
plt.show()

Summary

In this lab, you learned how to use recurrence rules in Matplotlib to place custom date ticks on a plot. You first set the recurrence rule using the rrulewrapper function, and then used the RRuleLocator and DateFormatter functions to set the tick locator and formatter. Finally, you plotted the data and set the x-axis ticks using the tick locator and formatter functions.

Other Python Tutorials you may like