TUTORIAL

Matplotlib 教程 - 在圖中放置文字

本教程介紹了繪圖中的 Matplotlib 文字,如何在繪圖中放置文字,以及如何在其中旋轉文字。

本頁內容

在本教程中,我們將學習如何在繪圖中放置文字。你既可以新增文字併為該文字指定座標位置,也可以將文字新增到特定圖上,並繪製一個直接指向該圖的箭頭。

座標軸 Text

matplotlib.axes.Axes.text(x, y, s, fontdict=None, withdash=False, **kwargs)

它將文字 s 新增到資料座標中位置 (x, y) 的軸上。

引數

名稱 資料型別 描述
x, y scalars 放置文字的位置
s str 文字
fontdict dictionary 覆蓋預設文字字型屬性的字典

座標軸 Text 基本示例

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

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

fig, ax = plt.subplots(1, figsize=(6, 4.5))
ax.plot(x, y, "r")
ax.text(2.0, 9.5, "Peak Value", fontsize=14)

ax.grid(True)

plt.show()

Matplotlib 文字

座標軸 Text 旋轉

座標軸 text 具有關鍵字引數- rotation,用於指定圖中的文字旋轉角度。rotation 的角度為 0 到 360(度)之間。

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

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

fig, ax = plt.subplots(1, figsize=(6, 4.5))
ax.plot(x, y, "r")
ax.text(1.3, 9.0, "Peak Value", fontsize=16, rotation=270)

ax.grid(True)

plt.show()

Matplotlib Text\_Rotation

座標軸 Text 旋轉角度說明

旋轉角度為逆時針方向。我們製作了一個演示指令碼來說明旋轉角度的定義。

import matplotlib.pyplot as plt
import numpy as np


def addtext(ax, props):
    for x in range(8):
        angle = 45 * x
        ax.text(0.5 + x, 0.5, "{} degree".format(angle), props, rotation=angle)
        ax.scatter(x + 0.5, 0.5, color="r")

    ax.set_yticks([0, 0.5, 1])
    ax.set_xlim(0, 8)
    ax.grid(True)


# the text bounding box
bbox = {"fc": "0.8", "pad": 0}

fig, axs = plt.subplots(1, 1, figsize=(8, 3))

addtext(axs, {"ha": "center", "va": "center", "bbox": bbox})
axs.set_xticks(np.arange(0, 8.1, 0.5), [])
axs.set_ylabel("center / center")

plt.show()

Matplotlib Text\_Rotation 角度演示

文字由其邊界框對齊,該邊界框是圍繞文字矩形的矩形框。文字將首先旋轉然後對齊。基本上,文字將居中 (x, y) 定位,圍繞該點旋轉,然後根據旋轉後文字的邊界框對齊。

因此,如果指定左對齊,底部對齊,則旋轉後的文字的邊界框的左下角將位於文字的 (x, y) 座標處。