# Matplotlib 教程 - 座標軸標題

Jinku Hu 2023年1月30日

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

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

## 座標軸上的多個標題

``````# -*- 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()
``````

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

``````# -*- 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()
``````

DelftStack.com 創辦人。Jinku 在機器人和汽車行業工作了8多年。他在自動測試、遠端測試及從耐久性測試中創建報告時磨練了自己的程式設計技能。他擁有電氣/ 電子工程背景，但他也擴展了自己的興趣到嵌入式電子、嵌入式程式設計以及前端和後端程式設計。