Matplotlib – Tick Formatters


Matplotlib – Tick Formatters



”;


Understanding Ticks and Tick Labels

In general graphs and plotting, ticks are the small lines that show the scale of x and y-axes, providing a clear representation of the value associated with each tick. Tick labels are the textual or numeric annotations associated with each tick on an axis, providing a clear representation of the value associated with each tick.

The following image represents the ticks and tick labels on a graph −


Tick Formatters Input Image

In this context Tick formatters, controls the appearance of the tick labels, specifying how the tick notations are displayed. This customization can include formatting options like specifying decimal places, adding units, using scientific notation, or applying date and time formats.

Tick Formatters in Matplotlib

Matplotlib allows users to customize tick properties, including locations and labels, through the matplotlib.ticker module. This module contains classes for configuring both tick locating and formatting. It provides a range of generic tick locators and formatters, as well as domain-specific custom ones.

To set the tick format, Matplotlib allows ypu to use either −

  • a format string,
  • a function,
  • or an instance of a Formatter subclass.

Applying Tick Formatters

Matplotlib provides a straightforward way to configure tick formatters using the set_major_formatter and set_minor_formatter functions. These functions enable you to set the major and minor tick label formats for a specific axis.

The syntax is as follows −

Syntax


ax.xaxis.set_major_formatter(xmajor_formatter)
ax.xaxis.set_minor_formatter(xminor_formatter)
ax.yaxis.set_major_formatter(ymajor_formatter)
ax.yaxis.set_minor_formatter(yminor_formatter)

String Formatting

String Formatting is a technique, which implicitly creates the StrMethodFormatter method, allowing you to use new-style format strings (str.format).

Example

In this example, the x-axis tick labels will be formatted using a string.


import matplotlib.pyplot as plt
from matplotlib import ticker

# Create a sample plot
fig, ax = plt.subplots(figsize=(7,4))
ax.plot([1, 2, 3, 4], [10, 20, 15, 20])

# Set up the major formatter for the x-axis
ax.xaxis.set_major_formatter(''{x} km'')
ax.set_title(''String Formatting'')
plt.show()

Output

On executing the above code we will get the following output −


Tick Formatters Example 1

Function Based Formatting

This approach provides a flexible way to customize tick labels using a user-defined function. The function should accept two inputs: x (the tick value) and pos (the position of the tick on the axis). Then it returns a string representing the desired tick label corresponding to the given inputs.

Example

This example demonstrates using a function to format x-axis tick labels.


from matplotlib.ticker import FuncFormatter
from matplotlib import pyplot as plt

def format_tick_labels(x, pos):
   return ''{0:.2f}%''.format(x)

# sample data
values = range(20)

# Create a plot
f, ax = plt.subplots(figsize=(7,4))
ax.plot(values)

# Set up the major formatter for the x-axis using a function
ax.xaxis.set_major_formatter(FuncFormatter(format_tick_labels))
ax.set_title(''Function Based Formatting'')
plt.show()

Output

On executing the above code we will get the following output −


Tick Formatters Example 2

Formatter Object Formatting

Formatter object Formatting allows for advanced customization of tick labels using specific formatter subclass. Some common Formatter subclasses include −

  • NullFormatter − This object ensures that no labels are displayed on the ticks.
  • StrMethodFormatter − This object utilizes the string str.format method for formatting tick labels.
  • FormatStrFormatter − This object employs %-style formatting for tick labels.
  • FuncFormatter − It define labels through a custum function.
  • FixedFormatter − It allows users to set label strings explicitly.
  • ScalarFormatter − It is the default formatter for scalars.
  • PercentFormatter − It format labels as percentages.

Example 1

The following example demonstrates how different Formatter Objects can be applied to the x-axis to achieve different formatting effects on tick labels.


from matplotlib import ticker
from matplotlib import pyplot as plt

# Create a plot
fig, axs = plt.subplots(5, 1, figsize=(7, 5))
fig.suptitle(''Formatter Object Formatting'', fontsize=16)

# Set up the formatter 
axs[0].xaxis.set_major_formatter(ticker.NullFormatter())
axs[0].set_title(''NullFormatter()'')

# Add other formatters 
axs[1].xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.3f}"))
axs[1].set_title(''StrMethodFormatter("{x:.3f}")'')

axs[2].xaxis.set_major_formatter(ticker.FormatStrFormatter("#%d"))
axs[2].set_title(''FormatStrFormatter("#%d")'')

axs[3].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))
axs[3].set_title(''ScalarFormatter(useMathText=True)'')

axs[4].xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5))
axs[4].set_title(''PercentFormatter(xmax=5)'')

plt.tight_layout()
plt.show()

Output

On executing the above code we will get the following output –


Tick Formatters Example 3

Example 2

This example demonstrates how to format tick labels on both the x-axis and y-axis using a string formatting method (StrMethodFormatter) to display the numbers with comma separators.


import matplotlib.pyplot as plt
from matplotlib.ticker import StrMethodFormatter

# Data
x = [10110, 20110, 40110, 6700]
y = [20110, 10110, 30110, 9700]

# Create plot
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x, y)

# Format tick labels for both x-axis and y-axis to include comma separators
ax.yaxis.set_major_formatter(StrMethodFormatter(''{x:,}''))
ax.xaxis.set_major_formatter(StrMethodFormatter(''{x:,}''))
# Show plot
plt.show()

Output

On executing the above code you will get the following output −


Tick Formatters Example 4

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *