Matplotlib - 刻度格式化器



理解刻度和刻度標籤

一般來說,在圖表和繪圖中,刻度是顯示x軸和y軸比例尺的小短線,清晰地表示每個刻度關聯的值。刻度標籤是與軸上每個刻度關聯的文字或數字註釋,清晰地表示每個刻度關聯的值。

下圖顯示了圖表上的刻度和刻度標籤:

Tick Formatters Input Image

在此背景下,**刻度格式化器**控制刻度標籤的外觀,指定刻度標記的顯示方式。此自定義可以包括格式選項,例如指定小數位數、新增單位、使用科學計數法或應用日期和時間格式。

Matplotlib中的刻度格式化器

Matplotlib允許使用者透過**matplotlib.ticker**模組自定義刻度屬性,包括位置和標籤。此模組包含用於配置刻度定位和格式化的類。它提供了一系列通用的刻度定位器和格式化器,以及特定領域的自定義刻度定位器和格式化器。

要設定刻度格式,Matplotlib允許您使用:

  • 一個**格式字串**,
  • 一個**函式**,
  • 或一個**Formatter子類**的例項。

應用刻度格式化器

Matplotlib提供了一種直接的方法來使用set_major_formatter和set_minor_formatter函式配置刻度格式化器。這些函式使您可以為特定軸設定主刻度和次刻度標籤格式。

語法如下:

語法

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)

字串格式化

字串格式化是一種技術,它隱式地建立StrMethodFormatter方法,允許您使用新式格式字串(str.format)。

示例

在這個示例中,x軸刻度標籤將使用字串進行格式化。

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

輸出

執行上述程式碼後,我們將得到以下輸出:

Tick Formatters Example 1

基於函式的格式化

這種方法提供了一種靈活的方式,可以使用**使用者定義**函式自定義刻度標籤。該函式應接受兩個輸入:x(刻度值)和pos(軸上刻度的位置)。然後它返回一個字串,表示與給定輸入對應的所需刻度標籤。

示例

此示例演示瞭如何使用函式格式化x軸刻度標籤。

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

輸出

執行上述程式碼後,我們將得到以下輸出:

Tick Formatters Example 2

格式化器物件格式化

格式化器物件格式化允許使用特定的格式化器子類高階自定義刻度標籤。一些常見的Formatter子類包括:

  • **NullFormatter** - 此物件確保刻度上不顯示任何標籤。
  • **StrMethodFormatter** - 此物件使用字串str.format方法格式化刻度標籤。
  • **FormatStrFormatter** - 此物件使用%-style格式化刻度標籤。
  • **FuncFormatter** - 它透過自定義函式定義標籤。
  • **FixedFormatter** - 它允許使用者顯式設定標籤字串。
  • **ScalarFormatter** - 它是標量的預設格式化器。
  • **PercentFormatter** - 它將標籤格式化為百分比。

示例1

以下示例演示瞭如何將不同的Formatter物件應用於x軸,以在刻度標籤上實現不同的格式化效果。

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

輸出

執行上述程式碼後,我們將得到以下輸出:

Tick Formatters Example 3

示例2

此示例演示瞭如何使用字串格式化方法(StrMethodFormatter)格式化x軸和y軸上的刻度標籤,以顯示帶逗號分隔符的數字。

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

輸出

執行上述程式碼後,您將得到以下輸出:

Tick Formatters Example 4
廣告