Matplotlib 教程 - 座標軸標題

Jinku Hu 2023年1月30日
  1. Matplotlib 座標軸標題
  2. 座標軸上的多個標題
  3. 將座標軸標題放置在繪圖內部
Matplotlib 教程 - 座標軸標題

在本教程中,我們將學習 Matplotlib 中的座標軸標題。

Matplotlib 座標軸標題

matplotlib.pyplot.title(label, fontdict=None, loc=None, **kwargs)

它用來設定當前軸的標題。

引數

名稱 資料型別 描述
label str 標籤文字
fontdict dict 標籤文字字型字典,例如字型系列、顏色、粗細和大小
loc str 標題的位置。它具有三個選項,{'center', 'left', 'right'}。預設選項是 center
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 4 * np.pi, 1000)
y = np.sin(x)

plt.figure(figsize=(4, 3))

plt.plot(x, y, "r")
plt.xlabel(
    "Time (s)",
    size=16,
)
plt.ylabel("Value", size=16)

plt.title(
    "Title Example",
    fontdict={"family": "serif", "color": "darkblue", "weight": "bold", "size": 18},
)

plt.grid(True)

plt.show()

Matplotlib 軸標題

plt.title(
    "Title Example",
    fontdict={"family": "serif", "color": "darkblue", "weight": "bold", "size": 18},
)

座標軸上的多個標題

一個軸最多可以包含三個標題 leftcenterright。特定標題的位置由 loc 引數指定。

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 4 * np.pi, 1000)
y = np.sin(x)

plt.figure(figsize=(8, 6))

plt.plot(x, y, "r")
plt.xlabel(
    "Time (s)",
    size=16,
)
plt.ylabel("Value", size=16)

plt.title(
    "Left title",
    fontdict={"family": "serif", "color": "darkblue", "weight": "bold", "size": 16},
    loc="left",
)

plt.title(
    "Center title",
    fontdict={"family": "monospace", "color": "red", "weight": "bold", "size": 16},
    loc="center",
)

plt.title(
    "Right title",
    fontdict={"family": "fantasy", "color": "black", "weight": "bold", "size": 16},
    loc="right",
)

plt.grid(True)

plt.show()

Matplotlib 軸 Title\_loc 引數

將座標軸標題放置在繪圖內部

你還可以使用 positon=(m, n) 或等效選項 x = m, y = n 將標題放置在繪圖內。在這裡,mn 是介於 0.0 和 1.0 之間的數字。

位置 (0, 0) 是圖的左下角,位置 (1.0, 1.0) 是右上角。

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 4 * np.pi, 1000)
y = np.sin(x)

plt.figure(figsize=(6, 4.5))

plt.plot(x, y, "r")
plt.xlabel("Time (s)", size=16)
plt.ylabel("Value", size=16)

plt.title(
    "Title Example",
    position=(0.5, 0.9),
    fontdict={"family": "serif", "color": "darkblue", "weight": "bold", "size": 16},
)

plt.show()

Matplotlib 軸 Title\_Inside 圖

作者: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn