Centeringels Between Ticks

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, we will learn how to center labels between ticks in a Matplotlib plot using Python. By default, tick labels are aligned relative to their associated tick, but there is no direct way to center the labels between ticks. However, we can place a label on the minor ticks in between the major ticks and hide the major tick labels and minor ticks to fake this behavior. We will use financial data for Google's stock price to demonstrate this technique.

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 python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/strings("`Strings`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") 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/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 python/comments -.-> lab-48600{{"`Centeringels Between Ticks`"}} matplotlib/importing_matplotlib -.-> lab-48600{{"`Centeringels Between Ticks`"}} matplotlib/figures_axes -.-> lab-48600{{"`Centeringels Between Ticks`"}} matplotlib/line_plots -.-> lab-48600{{"`Centeringels Between Ticks`"}} python/variables_data_types -.-> lab-48600{{"`Centeringels Between Ticks`"}} python/strings -.-> lab-48600{{"`Centeringels Between Ticks`"}} python/booleans -.-> lab-48600{{"`Centeringels Between Ticks`"}} python/type_conversion -.-> lab-48600{{"`Centeringels Between Ticks`"}} python/for_loops -.-> lab-48600{{"`Centeringels Between Ticks`"}} python/lists -.-> lab-48600{{"`Centeringels Between Ticks`"}} python/tuples -.-> lab-48600{{"`Centeringels Between Ticks`"}} python/importing_modules -.-> lab-48600{{"`Centeringels Between Ticks`"}} python/numerical_computing -.-> lab-48600{{"`Centeringels Between Ticks`"}} python/data_visualization -.-> lab-48600{{"`Centeringels Between Ticks`"}} python/build_in_functions -.-> lab-48600{{"`Centeringels Between Ticks`"}} end

Load the Financial Data

First, we need to load some financial data for Google's stock price using the Matplotlib cbook.get_sample_data() function. We will use the last 250 days of data.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cbook as cbook

## Load some financial data; Google's stock price
r = cbook.get_sample_data('goog.npz')['price_data'].view(np.recarray)
r = r[-250:]  ## get the last 250 days

Create the Plot

Next, we will create the plot using Matplotlib's subplots() function and plot the adjusted close price of Google's stock over time.

fig, ax = plt.subplots()
ax.plot(r.date, r.adj_close)

Set the Major and Minor Locators and Formatters

To center the labels between ticks, we need to set the major and minor locators and formatters for the x-axis. We will use the dates.MonthLocator() function to set the major and minor locators to the month and the dates.DateFormatter() function to format the minor tick labels to the month abbreviation.

import matplotlib.dates as dates
import matplotlib.ticker as ticker

ax.xaxis.set_major_locator(dates.MonthLocator())
## 16 is a slight approximation since months differ in number of days.
ax.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=16))

ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.xaxis.set_minor_formatter(dates.DateFormatter('%b'))

Remove the Major Tick Labels and Minor Ticks

To fake the behavior of centering the labels between ticks, we need to remove the major tick labels and minor ticks and only show the minor tick labels. We can do this using the tick_params() function and setting the tick1On and tick2On parameters to False.

## Remove the tick lines
ax.tick_params(axis='x', which='minor', tick1On=False, tick2On=False)

Align the Minor Tick Labels

Finally, we need to align the minor tick labels to the center between the major ticks. We can do this using the get_xticklabels() function and setting the minor parameter to True to get the minor tick labels. We can then loop through the labels and set the horizontal alignment to 'center'.

## Align the minor tick label
for label in ax.get_xticklabels(minor=True):
    label.set_horizontalalignment('center')
imid = len(r) // 2
ax.set_xlabel(str(r.date[imid].item().year))

Show the Plot

We can now show the plot using the show() function.

plt.show()

Summary

In this lab, we learned how to center labels between ticks in a Matplotlib plot using Python. We used financial data for Google's stock price to demonstrate this technique and followed the following steps:

  1. Loaded the financial data
  2. Created the plot
  3. Set the major and minor locators and formatters
  4. Removed the major tick labels and minor ticks
  5. Aligned the minor tick labels to the center between the major ticks
  6. Showed the plot.

Other Python Tutorials you may like