Python問題集を解いてみよう!!

【Python】グラフに縦線・横線を追加したい【Matplotlib】

当ページのリンクには広告が含まれています。
【Python】グラフに縦線・横線を追加したい【Matplotlib】

今回は 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()
上記の実行結果
xの平均値に縦線を描く

おまけで平均値を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()
上記の実行結果
yの平均値に横線を描く

Google Colaboratory

本記事に掲載しているコードは Google Colaboratory で動作を確認しています。

下記リンクからアクセスして、ご自身の Google ドライブにコピーしていただければ、すぐに実行できます。

Google Colaboratory の Python のバージョンが 3.8.16 に上がってました。

環境構築の不要な Google が提供している Web サービスなので、Python を学習中の方にはオススメです。

おわりに

今回は、

Matplotlib において、グラフの特定の位置に縦線または横線を描く方法

をご紹介しました。

以上です。

スポンサーリンク

【Python】グラフに縦線・横線を追加したい【Matplotlib】

この記事が気に入ったら
フォローしてね!

よかったらシェアしてね!
  • URLをコピーしました!

コメント

コメントする

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)

目次