【こつこつPython】Pythonでグラフにテキストを表示する方法|matplotlib.pyplot.text

Pythonでグラフに文字列を表示する方法です。
使用するのはPythonのmatplotlibライブラリのtext関数です。

import matplotlib.pyplot as plt

このようなデータを使用します。

x = [0, 1, 2, 3, 4, 5]
y = [0, 1, 2, 3, 4, 5]

まず、figure関数、plot関数、grid関数を使用してグラフを作成します。
grid関数を使用すると、グラフの縦と横に目盛り線をひけます。
実行します。

plt.figure(figsize=(8, 4))
plt.plot(x, y)
plt.grid()
plt.show()

グラフを表示できました。

次に、text関数を使用して、このグラフに"y=x"という文字列を表示させてみましょう。
引数に表示したい文字列のx座標、y座標、文字列を指定します。
実行します。

plt.figure(figsize=(8, 4))
plt.plot(x, y)
plt.grid()
plt.text(4, 3, "y=x")
plt.show()

x座標が4、y座標が3の位置に"y=x"という文字列を表示できました。

また、文字列の大きさ、色、配置を変えることもできます。
まず、文字列の大きさを変えてみましょう。
引数fontsize、またはsizeに文字列の大きさを指定します。
実行します。

plt.figure(figsize=(8, 4))
plt.plot(x, y)
plt.grid()
plt.text(4, 3, "y=x", fontsize=30)
plt.show()

文字列を大きく表示できました。

次に、文字列の色を変えてみましょう。
引数color、またはcに文字列の色を指定します。
実行します。

plt.figure(figsize=(8, 4))
plt.plot(x, y)
plt.grid()
plt.text(4, 3, "y=x", fontsize=30, color="red")
plt.show()

文字列を赤く表示できました。

最後に、文字列の配置を変えてみましょう。
引数horizontalalignment、またはhaに"left"、"center"、"right"のいずれかを選択します。
実行します。

plt.figure(figsize=(8, 4))
plt.plot(x, y)
plt.grid()
plt.text(4, 3, "y=x", fontsize=30, color="red", horizontalalignment="center")
plt.show()

文字列を中央寄せで表示できました。