Matplotlib text() / annotate() 関数


Matplotlib リファレンスドキュメント

text()グラフの指定座標にテキストを追加し、annotate()矢印付きの注釈を追加して、データポイントを正確に指し示すことができます。

関数定義

text()

matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)
Axes.text(x, y, s, fontdict=None, **kwargs)

annotate()

matplotlib.pyplot.annotate(text, xy, xytext=None, xycoords='data',
    textcoords=None, arrowprops=None, annotation_clip=None, **kwargs)
Axes.annotate(text, xy, xytext=None, xycoords='data',
    textcoords=None, arrowprops=None, annotation_clip=None, **kwargs)

パラメータ説明

text() のパラメータ

パラメータ説明
x, yテキスト位置の座標
s表示するテキスト文字列
fontsizeフォントサイズ
colorテキストの色
ha / horizontalalignment水平方向の配置:'center'、'right'、'left'
va / verticalalignment垂直方向の配置:'center'、'top'、'bottom'、'baseline'
rotation回転角度(度数)
fontweightフォントの太さ:'normal'、'bold'、'light'
bboxテキスト背景枠の属性。例:dict(facecolor='yellow', alpha=0.5)

annotate() 固有のパラメータ

パラメータ説明
text注釈テキストの内容
xy指し示す対象点の座標 (x, y)(矢印の先端)
xytextテキストを配置する位置の座標。デフォルトは None(テキストは xy の位置に配置)
xycoords / textcoordsxy / xytext の座標系:'data'、'axes fraction'、'figure fraction'、'offset points' など
arrowprops矢印属性の辞書。例:dict(arrowstyle='->', color='gray', lw=1.5)

annotate の核心的な価値は、xy と xytext で座標点とテキスト位置をそれぞれ指定し、矢印で両者を接続できることです。これは text() ではできません。

arrowprops でよく使う矢印スタイル

スタイル効果
'->'塗りつぶし三角矢印
'-'線なし
'<->'両方向矢印
'-[widthB=...,lengthB=...]'カスタム矩形矢印
'fancy'優雅な曲線矢印
'simple'シンプルな直線矢印

使用例

例1:基本的なテキスト追加 (text)

実例

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')

ax.plot(x, y, 'steelblue', linewidth=2)

# ピーク位置にテキストマーカーを追加
peak_idx = np.argmax(y)
ax.text(x[peak_idx], y[peak_idx] + 0.1,
        f'Peak: ({x[peak_idx]:.2f}, {y[peak_idx]:.2f})',
        fontsize=10, color='red',
        ha='center', va='bottom',
        fontweight='bold')

# 谷の位置にテキスト + 背景枠を追加
valley_idx = np.argmin(y)
ax.text(x[valley_idx], y[valley_idx] - 0.15,
        f'Valley: ({x[valley_idx]:.2f}, {y[valley_idx]:.2f})',
        fontsize=10, ha='center', va='top',
        bbox=dict(boxstyle='round,pad=0.3',
                  facecolor='yellow', alpha=0.7))

ax.set_title('text() - Adding Text at Specific Coordinates')
ax.set_xlabel('x')
ax.set_ylabel('sin(x)')
ax.grid(True, alpha=0.3)
plt.show()

例2:矢印による注釈 (annotate)

実例

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 50)
y = np.exp(-x/3) * np.sin(2 * x)  # 減衰振動

fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')
ax.plot(x, y, 'steelblue', linewidth=2, marker='o', markersize=4)

# 最初のピークを注釈(矢印がテキストからデータポイントを指す)
peak1_idx = np.argmax(y)
ax.annotate('1st Peak',
            xy=(x[peak1_idx], y[peak1_idx]),          # 矢印が指す点
            xytext=(x[peak1_idx] + 1.5, y[peak1_idx] + 0.2),  # テキスト位置
            arrowprops=dict(arrowstyle='-&gt;',
                            color='red', lw=1.5),
            fontsize=11, color='red', fontweight='bold')

# 減衰領域を注釈
ax.annotate('Decay region',
            xy=(.7, .3), xycoords='axes fraction',     # axes 座標を使用
            xytext=(0.5, 0.8), textcoords='axes fraction',
            arrowprops=dict(arrowstyle='fancy',
                            color='green',
                            connectionstyle='arc3,rad=0.3'),
            fontsize=11, color='green',
            bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))

ax.set_title('annotate() - Annotations with Arrows')
ax.set_xlabel('Time (s)')
ax.set_ylabel('Amplitude')
ax.grid(True, alpha=0.3)
plt.show()

例3:数式の注釈と座標系

実例

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 4*np.pi, 200)
y1 = np.sin(x)
y2 = np.cos(x)

fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')
ax.plot(x, y1, 'blue', label='sin(x)')
ax.plot(x, y2, 'red', label='cos(x)')

# グラフの固定位置に数式で注釈
ax.text(0.02, 0.95,
        r'$f(x) = sin(x)$',
        transform=ax.transAxes,    # Axes の相対座標を使用 (0-1)
        fontsize=14, color='blue',
        verticalalignment='top',
        bbox=dict(boxstyle='round', facecolor='lightblue', alpha=0.5))

ax.text(0.02, 0.82,
        r'$g(x) = cos(x)$',
        transform=ax.transAxes,
        fontsize=14, color='red',
        verticalalignment='top',
        bbox=dict(boxstyle='round', facecolor='lightcoral', alpha=0.5))

ax.set_title(r'Math Formula with LaTeX: $sum_{i=1}^{n} x_i$')
ax.set_xlabel('x (radians)')
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()
print("サンプル: math annotation displayed")

よくある質問

text と annotate の違いは何ですか?

text()指定した座標にテキストを配置するだけなので、ラベルや説明の追加に適しています。

annotate()テキストとデータポイントを結ぶ矢印を追加できるので、重要な位置を正確に注釈するのに適しています。

テキストで数式を使用するにはどうすればよいですか?

LaTeX 構文を使用します:r'$alpha + beta$'r プレフィックスは raw 文字列を表し、$...$ 内の内容は数式としてレンダリングされます。

システムに LaTeX がインストールされているか、Matplotlib 組み込みの mathtext レンダラーを使用する必要があります。


Matplotlib リファレンスドキュメント

その他の拡張