Matplotlib チュートリアル - プロットにテキストを配置

このチュートリアルでは、プロットにテキストを配置する方法について学習します。テキストを追加してそのテキストに座標位置を与えるか、特定のプロットにテキストを追加して、そのプロットを直接指す矢印を描くこともできます。
Matplotlib 軸の Test
matplotlib.axes.Axes.text(x, y, s, fontdict=None, withdash=False, **kwargs)
データ座標の位置 (x, y)
の座標軸にテキスト s
を追加します。
パラメーター
名前 | データ・タイプ | 説明 |
---|---|---|
x, y |
scalars |
テキストを配置する位置 |
s |
str |
注釈テキスト |
fontdict |
dictionary |
デフォルトのテキストフォントプロパティをオーバーライドする辞書 |
Matplotlib 軸のテキスト
の基本的な例
# -*- 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 軸のテキスト
回転
Axes の text
には、キーワード引数-プロット内のテキストの回転角度を指定する 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 軸のテキスト
回転角度の説明
回転角度は反時計回りの方向です。回転角度の定義を説明するデモスクリプトを作成します。
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, .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()
テキストは、テキストの長方形を囲む長方形のボックスである境界ボックスによって整列されます。テキストは最初に回転され、次に整列されます。基本的に、テキストは (x, y)
の位置で中央揃えされ、この点を中心に回転され、回転されたテキストの境界ボックスに従って整列されます。
したがって、左下揃えを指定すると、回転したテキストの境界ボックスの左下は、テキストの (x, y)
座標になります。
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