今回は Matplotlib において、グラフの特定の位置に縦線または横線を描く方法をご紹介します。
目次
元のグラフ
まずは元のグラフを描きましょう。
今回は次のようなランダムな値の散布図を描いてみます。
import matplotlib.pyplot as plt
import random
x = [random.randrange(100) for i in range(100)]
y = [random.randrange(100) for i in range(100)]
fig = plt.figure(
figsize = (6, 4),
dpi = 100,
tight_layout = True,
)
ax = fig.add_subplot(
title = 'add_line',
xlabel = 'x',
ylabel = 'y',
)
ax.scatter(x, y, color='blue')
ax.grid(True, alpha=0.5)
plt.show()
上記の実行結果

このグラフに縦線・横線を描いていきます。
x の平均値に縦線を描く
グラフにしたデータの平均値をグラフ上で分かりやすくしたい、というケースを想定して、x の平均値に縦線を描いてみます。axvline()
を使用して縦線を描きます。
import matplotlib.pyplot as plt
import random
x = [random.randrange(100) for i in range(100)]
y = [random.randrange(100) for i in range(100)]
# x の平均値を求める
x_avg = sum(x) / len(x)
fig = plt.figure(
figsize = (6, 4),
dpi = 100,
tight_layout = True,
)
ax = fig.add_subplot(
title = 'add_line',
xlabel = 'x',
ylabel = 'y',
)
ax.scatter(x, y, color='blue')
ax.grid(True, alpha=0.5)
# x の平均値に縦線を入れる
ax.axvline(x_avg, color="red")
ax.text(x_avg, -10, x_avg, ha='center', color="red")
plt.show()
上記の実行結果

おまけで平均値をtext()
で表示しました。
yの平均値に横線を描く
続いて、y の平均値に横線を描きます。
横線はaxhline()
を使用します。
import matplotlib.pyplot as plt
import random
x = [random.randrange(100) for i in range(100)]
y = [random.randrange(100) for i in range(100)]
# x、y の平均値を求める
x_avg = sum(x) / len(x)
y_avg = sum(y) / len(y)
fig = plt.figure(
figsize = (6, 4),
dpi = 100,
tight_layout = True,
)
ax = fig.add_subplot(
title = 'add_line',
xlabel = 'x',
ylabel = 'y',
)
ax.scatter(x, y, color='blue')
ax.grid(True, alpha=0.5)
# x の平均値に縦線を入れる
ax.axvline(x_avg, color="red")
ax.text(x_avg, -10, x_avg, ha='center', color="red")
# y の平均値に横線を入れる
ax.axhline(y_avg, color="red")
ax.text(-13, y_avg, y_avg, va='center', color="red")
plt.show()
上記の実行結果

Google Colaboratory
本記事に掲載しているコードは Google Colaboratory で動作を確認しています。
下記リンクからアクセスして、ご自身の Google ドライブにコピーしていただければ、すぐに実行できます。
環境構築の不要な Google が提供している Web サービスなので、Python を学習中の方にはオススメです。
おわりに
今回は、
Matplotlib において、グラフの特定の位置に縦線または横線を描く方法
をご紹介しました。
以上です。
コメント