Matplotlib Date Plotting

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, we will learn how to create date plots using Matplotlib in Python. We will use the matplotlib.dates module to convert datetime objects to Matplotlib's internal representation. We will also learn how to format the tick labels on the x-axis to display dates in a readable format.

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`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) 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`") matplotlib/PlotCustomizationGroup -.-> matplotlib/grid_config("`Grid Configuration`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48656{{"`Matplotlib Date Plotting`"}} matplotlib/figures_axes -.-> lab-48656{{"`Matplotlib Date Plotting`"}} matplotlib/line_plots -.-> lab-48656{{"`Matplotlib Date Plotting`"}} matplotlib/grid_config -.-> lab-48656{{"`Matplotlib Date Plotting`"}} python/variables_data_types -.-> lab-48656{{"`Matplotlib Date Plotting`"}} python/booleans -.-> lab-48656{{"`Matplotlib Date Plotting`"}} python/for_loops -.-> lab-48656{{"`Matplotlib Date Plotting`"}} python/lists -.-> lab-48656{{"`Matplotlib Date Plotting`"}} python/tuples -.-> lab-48656{{"`Matplotlib Date Plotting`"}} python/importing_modules -.-> lab-48656{{"`Matplotlib Date Plotting`"}} python/data_collections -.-> lab-48656{{"`Matplotlib Date Plotting`"}} python/data_visualization -.-> lab-48656{{"`Matplotlib Date Plotting`"}} python/build_in_functions -.-> lab-48656{{"`Matplotlib Date Plotting`"}} end

Import necessary libraries

We will start by importing the necessary libraries, including matplotlib.pyplot, matplotlib.cbook, and matplotlib.dates.

import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import matplotlib.dates as mdates

Load data

Next, we will load the data that we want to plot. We will use a numpy record array from Yahoo csv data with fields date, open, high, low, close, volume, adj_close from the mpl-data/sample_data directory. The record array stores the date as an np.datetime64 with a day unit ('D') in the date column.

data = cbook.get_sample_data('goog.npz')['price_data']

Create subplots

We will create three subplots to show different formatting options for the tick labels.

fig, axs = plt.subplots(3, 1, figsize=(6.4, 7), layout='constrained')

Plot data

We will plot the data on all three subplots using the plot function.

for ax in axs:
    ax.plot('date', 'adj_close', data=data)
    ax.grid(True)
    ax.set_ylabel(r'Price [\$]')

Format tick labels using default formatter

We will format the tick labels on the first subplot using the default formatter.

ax = axs[0]
ax.set_title('DefaultFormatter', loc='left', y=0.85, x=0.02, fontsize='medium')
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=(1, 7)))
ax.xaxis.set_minor_locator(mdates.MonthLocator())

Format tick labels using concise formatter

We will format the tick labels on the second subplot using the concise formatter.

ax = axs[1]
ax.set_title('ConciseFormatter', loc='left', y=0.85, x=0.02, fontsize='medium')
ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()))

Format tick labels manually

We will format the tick labels on the third subplot manually using DateFormatter to format the dates using the format strings documented at datetime.date.strftime.

ax = axs[2]
ax.set_title('Manual DateFormatter', loc='left', y=0.85, x=0.02, fontsize='medium')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))
for label in ax.get_xticklabels(which='major'):
    label.set(rotation=30, horizontalalignment='right')

Display plot

Finally, we will display the plot using the show function.

plt.show()

Summary

In this lab, we learned how to create date plots using Matplotlib in Python. We used the matplotlib.dates module to convert datetime objects to Matplotlib's internal representation. We also learned how to format the tick labels on the x-axis to display dates in a readable format.

Other Python Tutorials you may like