Matplotlib 简明教程

Matplotlib - Tick Formatters

Understanding Ticks and Tick Labels

在一般图像和曲线图中,刻度线是显示 x 轴和 y 轴刻度的线,提供与每个刻度线相关的值的清晰表示。刻度标签是与每个轴上的每个刻度线相关联的文本或数值注释,提供与每个刻度线相关联的值的清晰表示。

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

在此上下文中 Tick formatters ,控制刻度标签的外观,指定如何显示刻度符号。此自定义可以包括格式化选项,如指定小数位数、添加单位、使用科学计数法或应用日期和时间格式。

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 允许用户通过 matplotlib.ticker 模块自定义刻度属性,包括位置和标签。此模块包含用于配置刻度位置和格式的类。它提供一系列通用刻度位置器和格式化器,以及针对特定领域的自定义刻度位置器和格式化器。

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.

为了设置刻度格式,Matplotlib 允许您使用 −

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

  1. a format string,

  2. a function,

  3. or an instance of a Formatter subclass.

Applying Tick Formatters

Matplotlib 通过 set_major_formatterset_minor_formatter 函数提供了一种直接配置刻度格式化程序的方法。这些函数允许您设置特定轴的主次刻度标签格式。

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 −

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

字符串格式化是一种技术,它隐式创建了 StrMethodFormatter 方法,允许您使用新式格式字符串(str.format)。

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

Example

在此示例中,x 轴刻度标签将使用字符串格式化。

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()

执行上述代码,我们将得到以下输出 −

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

tick formatters ex1

Function Based Formatting

此方法提供了一种通过 user-defined 函数自定义刻度标签的灵活方式。该函数应接受两个输入:x(刻度值)和 pos(刻度在轴上的位置)。然后,它返回一个表示与给定输入相对应的所需刻度标签的字符串。

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

此示例演示了使用函数格式化 x 轴刻度标签。

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()

执行上述代码,我们将得到以下输出 −

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

tick formatters ex2

Formatter Object Formatting

格式化程序对象格式化允许使用特定的格式化程序子类对刻度标签进行高级自定义。一些常见的 Formatter 子类包括:

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

  1. NullFormatter − This object ensures that no labels are displayed on the ticks.

  2. StrMethodFormatter − This object utilizes the string str.format method for formatting tick labels.

  3. FormatStrFormatter − This object employs %-style formatting for tick labels.

  4. FuncFormatter − It define labels through a custum function.

  5. FixedFormatter − It allows users to set label strings explicitly.

  6. ScalarFormatter − It is the default formatter for scalars.

  7. PercentFormatter − It format labels as percentages.

Example 1

以下示例演示了如何将不同的 Formatter 对象应用于 x 轴,以实现刻度标签的不同格式化效果。

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()

执行上述代码,我们将得到以下输出:

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

tick formatters ex3

Example 2

此示例演示了如何使用字符串格式化方法(StrMethodFormatter)在 x 轴和 y 轴上设置刻度标签的格式,以逗号分隔符显示数字。

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()

执行上述代码时,您将获得以下输出 -

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

tick formatters ex4