Matplotlib のサブプロットにテキストを追加する方法


次の構文を使用して、Matplotlib の特定のサブプロットにテキストを追加できます。

 import matplotlib. pyplot as plt

#define subplot layout
fig, ax = plt. subplots (2, 1, figsize=(7,4))

#add text at specific locations in subplots
ax[0]. text (1.5, 20, ' Here is some text in the first subplot ')
ax[1]. text (2, 10, ' Here is some text in the second subplot ')

この特定の例では、 (x,y) 座標(1,5,20)の最初のサブプロットにテキストを追加し、 (x,y) 座標(2,10)の 2 番目のサブプロットにテキストを追加します。

次の例は、この構文を実際に使用する方法を示しています。

例: Matplotlib のサブプロットにテキストを追加する

次のコードは、Matplotlib で 2 行 1 列のレイアウトに配置された 2 つのサブプロットを作成する方法を示しています。

 import matplotlib. pyplot as plt

#define subplot layout
fig, ax = plt. subplots (2, 1, figsize=(7,4))
fig. tight_layout ()

#define data
x = [1, 2, 3]
y = [7, 13, 24]

#create subplots
ax[0]. plot (x,y,color=' red ')
ax[1]. plot (x,y,color=' blue ') 

次の構文を使用して、各サブプロットの特定の位置にテキストを追加できます。

 import matplotlib. pyplot as plt

#define subplot layout
fig, ax = plt. subplots (2, 1, figsize=(7,4))
fig. tight_layout ()

#define data
x = [1, 2, 3]
y = [7, 13, 24]

#create subplots
ax[0]. plot (x,y,color=' red ')
ax[1]. plot (x,y,color=' blue ')

#add text at specific locations in subplots
ax[0]. text (1.5, 20, ' Here is some text in the first subplot ')
ax[1]. text (2, 10, ' Here is some text in the second subplot ')

Matplotlib はサブプロットにテキストを追加します

指定した (x,y) 座標で各サブプロットにテキストが追加されていることに注意してください。

最初のサブプロットを参照するためにax[0]を使用し、2 番目のサブプロットを参照するためにax[1]を使用したことに注意してください。

次に、 text()関数を使用して、(x, y) 座標と各サブプロットで使用する特定のテキストを指定しました。

追加リソース

次のチュートリアルでは、Matplotlib で他の一般的なタスクを実行する方法を説明します。

Matplotlib でサブプロットにタイトルを追加する方法
Matplotlib でサブプロット サイズを調整する方法
Matplotlib サブプロット間の間隔を調整する方法

コメントを追加する

メールアドレスが公開されることはありません。 が付いている欄は必須項目です