0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ホームランの軌跡や速度&角度のデータ (大谷翔平さん vs 全体)

Posted at

このプログラムでは、大谷翔平選手の打球データ(打球速度、打ち上げ角、ホームラン距離など)を解析し、以下のグラフを表示しています。

  1. 打ち上げ角と打球速度の散布図(全打席と安打のみ)
  2. 打ち上げ角と打球速度の散布図(全打席と安打のみ、1塁打・2塁打・3塁打・ホームラン別)
  3. ホームランの飛距離と打ち上げ角の散布図(全選手と大谷翔平選手)
  4. ホームランの飛距離と打球速度の散布図(全選手と大谷翔平選手)
  5. 大谷翔平選手のホームランの弾道グラフ
  6. 全選手のホームランの弾道グラフ(大谷翔平選手は赤色で強調表示)
  7. 打ち上げ角ごとのアウト確率の棒グラフ

データ準備

!pip install pybaseball
from pybaseball import statcast
df = statcast(start_dt='2022-03-31', end_dt='2022-12-31')
df_ohtani = df[df['batter'] == 660271]

大谷翔平さんのヒットデータを抜き取り

import matplotlib.pyplot as plt
ohtani_hit_data = df_ohtani[df_ohtani['events'].isin(['single', 'double', 'triple', 'home_run'])]
ohtani_single_data = ohtani_hit_data[ohtani_hit_data['events'] == 'single']
ohtani_double_data = ohtani_hit_data[ohtani_hit_data['events'] == 'double']
ohtani_triple_data = ohtani_hit_data[ohtani_hit_data['events'] == 'triple']
ohtani_home_run_data = ohtani_hit_data[ohtani_hit_data['events'] == 'home_run']


大谷翔平さんのヒットデータ(打球の速さと角度)

このコードは、大谷翔平さんのヒットデータ(打球の速さと角度)を分析して、グラフで表示しています。データは、シングルヒット、2塁打、3塁打、ホームランの4種類に分けられています。グラフには、打球の角度と速さがプロットされ、どのような打球がヒットにつながるかを見ることができます。

ohtani_hit_data_clean = ohtani_hit_data.dropna(subset=['launch_angle', 'launch_speed'])

plt.scatter(ohtani_hit_data_clean['launch_angle'], ohtani_hit_data_clean['launch_speed'])
plt.xlabel('Launch Angle (degrees)')
plt.ylabel('Launch Speed (mph)')
plt.title('Scatter plot of Launch Angle vs. Launch Speed for Shohei Ohtani')

# 罫線
plt.grid(which='both', linestyle='--', color='gray', alpha=0.5)

plt.show()


大谷翔平さんのヒットデータ(打球の速さと角度)・ 色分け

このコードでは、大谷翔平さんの打球データをシングルヒット、2塁打、3塁打、ホームランごとに色分けしてグラフに表示しています。打球の角度と速さをそれぞれのヒット別にプロットし、青色はシングルヒット、緑色は2塁打、オレンジ色は3塁打、赤色はホームランを表しています。グラフには、打球の角度と速さが表示されており、それぞれのヒットがどのような打球になるかを見ることができます。また、凡例が付けられており、どの色がどのヒットを表しているかが分かりやすくなっています。

ohtani_single_data_clean = ohtani_single_data.dropna(subset=['launch_angle', 'launch_speed'])
ohtani_double_data_clean = ohtani_double_data.dropna(subset=['launch_angle', 'launch_speed'])
ohtani_triple_data_clean = ohtani_triple_data.dropna(subset=['launch_angle', 'launch_speed'])
ohtani_home_run_data_clean = ohtani_home_run_data.dropna(subset=['launch_angle', 'launch_speed'])

plt.scatter(ohtani_single_data_clean['launch_angle'], ohtani_single_data_clean['launch_speed'], color='blue', label='Single')
plt.scatter(ohtani_double_data_clean['launch_angle'], ohtani_double_data_clean['launch_speed'], color='green', label='Double')
plt.scatter(ohtani_triple_data_clean['launch_angle'], ohtani_triple_data_clean['launch_speed'], color='orange', label='Triple')
plt.scatter(ohtani_home_run_data_clean['launch_angle'], ohtani_home_run_data_clean['launch_speed'], color='red', label='Home Run')

plt.xlabel('Launch Angle (degrees)')
plt.ylabel('Launch Speed (mph)')
plt.title('Scatter plot of Launch Angle vs. Launch Speed for Shohei Ohtani')
plt.legend()

# 罫線
plt.grid(which='both', linestyle='--', color='gray', alpha=0.5)

plt.show()


データ欠損値の整理

このコードでは、すべての選手の打球データをシングルヒット、2塁打、3塁打、ホームランごとに分類しています。次に、それぞれのヒット別のデータから、打球の角度と速さに欠損値(空白や不明な値)があるデータを削除しています。

all_hit_data = df[df['events'].isin(['single', 'double', 'triple', 'home_run'])]

all_single_data = all_hit_data[all_hit_data['events'] == 'single']
all_double_data = all_hit_data[all_hit_data['events'] == 'double']
all_triple_data = all_hit_data[all_hit_data['events'] == 'triple']
all_home_run_data = all_hit_data[all_hit_data['events'] == 'home_run']

all_single_data_clean = all_single_data.dropna(subset=['launch_angle', 'launch_speed'])
all_double_data_clean = all_double_data.dropna(subset=['launch_angle', 'launch_speed'])
all_triple_data_clean = all_triple_data.dropna(subset=['launch_angle', 'launch_speed'])
all_home_run_data_clean = all_home_run_data.dropna(subset=['launch_angle', 'launch_speed'])


全体 vs 大谷さんのヒットデータ(打球の速さと角度)・ 色分け

このコードでは、すべての選手の打球データをグラフに表示しています。シングルヒット、2塁打、3塁打、ホームランをそれぞれの色で表し、青色はシングルヒット、緑色は2塁打、オレンジ色は3塁打、赤色はホームランとなっています。各点の透明度は0.1に設定されており、データの重なりを見やすくしています。

グラフには、打球の角度と速さが表示されており、それぞれのヒットがどのような打球になるかを見ることができます。凡例も付けられており、どの色がどのヒットを表しているかが分かりやすくなっています。

plt.scatter(all_single_data_clean['launch_angle'], all_single_data_clean['launch_speed'], color='blue', label='Single', alpha=0.1)
plt.scatter(all_double_data_clean['launch_angle'], all_double_data_clean['launch_speed'], color='green', label='Double', alpha=0.1)
plt.scatter(all_triple_data_clean['launch_angle'], all_triple_data_clean['launch_speed'], color='orange', label='Triple', alpha=0.1)
plt.scatter(all_home_run_data_clean['launch_angle'], all_home_run_data_clean['launch_speed'], color='red', label='Home Run', alpha=0.1)

plt.xlabel('Launch Angle (degrees)')
plt.ylabel('Launch Speed (mph)')
plt.title('Scatter plot of Launch Angle vs. Launch Speed for MLB')
plt.legend()

# 罫線
plt.grid(which='both', linestyle='--', color='gray', alpha=0.5)

plt.show()


ホームランデータ ・ 打球の距離と角度

このコードでは、すべての選手のホームランデータに基づいて、打球の距離と角度をグラフに表示しています。まず、打球の距離と角度に欠損値(空白や不明な値)があるデータを削除しています。次に、打球の距離(横軸)と打球の角度(縦軸)をプロットして、ホームランになる打球がどのような特徴を持っているかを視覚化しています。

グラフのタイトルは、「Scatter plot of Hit Distance vs. Launch Angle for Home Runs」となっており、打球の距離と角度の関係を示しています。

all_home_run_data_clean = all_home_run_data.dropna(subset=['hit_distance_sc', 'launch_angle'])

plt.scatter(all_home_run_data_clean['hit_distance_sc'], all_home_run_data_clean['launch_angle'])
plt.xlabel('Hit Distance (ft)')
plt.ylabel('Launch Angle (degrees)')
plt.title('Scatter plot of Hit Distance vs. Launch Angle for Home Runs')
plt.grid(which='both', linestyle='--', color='gray', alpha=0.5)
plt.show()


ホームランデータ ・ 打球の距離と角度 (全体vs大谷さん)

このコードでは、すべての選手のホームランデータと大谷翔平さんのホームランデータを比較するグラフを作成しています。まず、打球の距離をフィートからメートルに変換しています。次に、すべての選手のホームランデータ(青色)と大谷翔平さんのホームランデータ(赤色)を、打球の距離(横軸)と打球の角度(縦軸)でプロットしています。

グラフのタイトルは、「Scatter plot of Hit Distance vs. Launch Angle for Home Runs」となっており、打球の距離と角度の関係を示しています。

# ft to m conversion
all_home_run_data_clean['hit_distance_m'] = all_home_run_data_clean['hit_distance_sc'] * 0.3048
ohtani_home_run_data_clean['hit_distance_m'] = ohtani_home_run_data_clean['hit_distance_sc'] * 0.3048

plt.scatter(all_home_run_data_clean['hit_distance_m'], all_home_run_data_clean['launch_angle'], label='All Players')
plt.scatter(ohtani_home_run_data_clean['hit_distance_m'], ohtani_home_run_data_clean['launch_angle'], color='red', label='Shohei Ohtani')
plt.xlabel('Hit Distance (m)')
plt.ylabel('Launch Angle (degrees)')
plt.title('Scatter plot of Hit Distance vs. Launch Angle for Home Runs')
plt.grid(which='both', linestyle='--', color='gray', alpha=0.5)
plt.legend()
plt.show()


ホームランデータ ・ 打球の距離と打球の速さ (全体vs大谷さん)

このコードでは、すべての選手のホームランデータと大谷翔平さんのホームランデータを比較するグラフを作成しています。グラフでは、打球の距離(横軸)と打球の速さ(縦軸)をプロットしています。すべての選手のホームランデータは青色で表され、大谷翔平さんのホームランデータは赤色で表示されています。

グラフのタイトルは、「Scatter plot of Hit Distance vs. Launch Speed for Home Runs」となっており、打球の距離と速さの関係を示しています。

plt.scatter(all_home_run_data_clean['hit_distance_m'], all_home_run_data_clean['launch_speed'], label='All Players')
plt.scatter(ohtani_home_run_data_clean['hit_distance_m'], ohtani_home_run_data_clean['launch_speed'], color='red', label='Shohei Ohtani')
plt.xlabel('Hit Distance (m)')
plt.ylabel('Launch Speed (mph)')
plt.title('Scatter plot of Hit Distance vs. Launch Speed for Home Runs')
plt.grid(which='both', linestyle='--', color='gray', alpha=0.5)
plt.legend()
plt.show()


ホームランの打球の軌跡 (大谷翔平さん)

このコードでは、大谷翔平さんのホームランの打球の軌跡をグラフに描画しています。まず、compute_trajectory関数を定義して、打球の距離、打球の速さ、打球の角度をもとに、打球の軌跡(x軸:距離、y軸:高さ)を計算しています。

次に、ohtani_home_run_data_cleanの各行に対して、compute_trajectory関数を使用して打球の軌跡を計算し、グラフにプロットしています。これにより、大谷翔平さんのホームランの打球がどのように飛んでいるかを視覚化できます。

グラフのタイトルは「Projectile motion of Shohei Ohtani home runs」となっており、大谷翔平さんのホームランの打球の軌跡を示しています。

import numpy as np
import matplotlib.pyplot as plt

def compute_trajectory(hit_distance, launch_speed, launch_angle):
    launch_speed = launch_speed * 1609.34 / 3600  # Convert mph to m/s
    launch_angle = np.radians(launch_angle)  # Convert degrees to radians
    g = 9.81  # Gravity acceleration in m/s^2

    t_flight = 2 * launch_speed * np.sin(launch_angle) / g
    t = np.linspace(0, t_flight, num=1000)
    x = launch_speed * np.cos(launch_angle) * t
    y = launch_speed * np.sin(launch_angle) * t - 0.5 * g * t ** 2

    # Scale the x-axis to match the hit_distance
    x = x * (hit_distance / max(x))

    return x, y

# Plot trajectories for each home run
plt.figure(figsize=(10, 6))
for index, row in ohtani_home_run_data_clean.iterrows():
    hit_distance = row['hit_distance_sc'] * 0.3048  # Convert ft to m
    launch_speed = row['launch_speed']
    launch_angle = row['launch_angle']

    x, y = compute_trajectory(hit_distance, launch_speed, launch_angle)
    plt.plot(x, y)

plt.xlabel('Distance (m)')
plt.ylabel('Height (m)')
plt.title('Projectile motion of Shohei Ohtani home runs')
plt.grid(which='both', linestyle='--', color='gray', alpha=0.5)
plt.show()

compute_trajectory関数は、打球の距離、打球の速さ、打球の角度を引数として受け取り、打球の軌跡を計算するための関数です。以下に、関数内で行われている主な計算について説明します。

  1. 打球の速さをマイル毎時(mph)からメートル毎秒(m/s)に変換します。
  2. 打球の角度を度数法から弧度法に変換します。
  3. 重力加速度(g)を定義します。これは地球上での重力の強さを表す値で、約9.81 m/s²です。
  4. 打球の飛行時間(t_flight)を計算します。これは、打球が地面に戻るまでの時間です。
  5. t_flightを0からt_flightまでの間で1000等分した時刻の配列(t)を作成します。
  6. 時刻tにおける打球のx座標(横方向の距離)とy座標(高さ)を計算します。この計算では、重力の影響を考慮しています。
  7. x軸の最大値が実際の打球距離と一致するように、x座標をスケーリング(調整)します。

最後に、x座標とy座標の配列を返します。これらの値は、打球の軌跡をグラフに描画する際に使用されます。


ホームランの打球の軌跡 (大谷翔平さん vs 全体)

このコードでは、すべての選手のホームランの打球の軌跡をグラフに描画し、大谷翔平さんのホームランの軌跡を赤色で強調しています。

まず、all_home_run_data_cleanの各行に対して、compute_trajectory関数を使用して打球の軌跡を計算し、グレーの薄い色でグラフにプロットしています。これにより、すべての選手のホームランの打球の軌跡を表示しています。

次に、ohtani_home_run_data_cleanの各行に対して、compute_trajectory関数を使用して打球の軌跡を計算し、赤色でグラフにプロットしています。これにより、大谷翔平さんのホームランの打球の軌跡を強調表示しています。

グラフのタイトルは「Projectile motion of MLB home runs (Ohtani in red)」となっており、大谷翔平さんのホームランの打球の軌跡を赤色で強調表示していることを示しています。

# Plot trajectories for all home runs
plt.figure(figsize=(12, 8))

# Plot all home runs
for index, row in all_home_run_data_clean.iterrows():
    hit_distance = row['hit_distance_sc'] * 0.3048  # Convert ft to m
    launch_speed = row['launch_speed']
    launch_angle = row['launch_angle']

    x, y = compute_trajectory(hit_distance, launch_speed, launch_angle)
    plt.plot(x, y, color='gray', alpha=0.3)

# Plot Ohtani's home runs with a different color
for index, row in ohtani_home_run_data_clean.iterrows():
    hit_distance = row['hit_distance_sc'] * 0.3048  # Convert ft to m
    launch_speed = row['launch_speed']
    launch_angle = row['launch_angle']

    x, y = compute_trajectory(hit_distance, launch_speed, launch_angle)
    plt.plot(x, y, color='red')

plt.xlabel('Distance (m)')
plt.ylabel('Height (m)')
plt.title('Projectile motion of MLB home runs (Ohtani in red)')
plt.grid(which='both', linestyle='--', color='gray', alpha=0.5)
plt.show()


打球の角度(打ち上げ角)ごとにアウトの確率を計算し、棒グラフで表示

このコードでは、打球の角度(打ち上げ角)ごとにアウトの確率を計算し、棒グラフで表示しています。

  1. angle_rangesは、-90度から90度までの範囲を10度刻みで表現しています。
  2. out_probabilitiesは、角度範囲ごとのアウト確率を格納するリストです。
  3. all_out_data_cleanは、アウトになった打球データを含むデータフレームです。
  4. all_hit_data_cleanは、全ての打球データ(安打とアウトを含む)を含むデータフレームです。

次に、各角度範囲ごとに以下の処理を行っています。

  1. 角度範囲内の打球データをフィルタリングします。
  2. その範囲内でのアウト数と総打数から、アウト確率を計算します。
  3. 計算されたアウト確率をout_probabilitiesリストに追加します。

最後に、plt.bar関数を使って、角度範囲ごとのアウト確率を棒グラフで表示します。x軸には打ち上げ角(度数)が、y軸にはアウト確率が表示されます。グラフのタイトルは「Out Probability by Launch Angle」となっています。

# Calculate out probabilities
angle_ranges = np.arange(-90, 91, 10)
out_probabilities = []

all_out_data = df[df['events'] == 'field_out']
all_out_data_clean = all_out_data.dropna(subset=['launch_angle', 'launch_speed'])

all_hit_data_clean = df[df['events'].isin(['single', 'double', 'triple', 'home_run', 'field_out'])].dropna(subset=['launch_angle', 'launch_speed'])

for i in range(len(angle_ranges) - 1):
    lower_bound = angle_ranges[i]
    upper_bound = angle_ranges[i + 1]

    # Filter data by angle range
    angle_range_data = all_hit_data_clean[(all_hit_data_clean['launch_angle'] >= lower_bound) &
                                          (all_hit_data_clean['launch_angle'] < upper_bound)]

    # Calculate out probability
    total_hits = len(angle_range_data)
    outs = len(all_out_data_clean[(all_out_data_clean['launch_angle'] >= lower_bound) & (all_out_data_clean['launch_angle'] < upper_bound)])
    out_probability = outs / total_hits if total_hits > 0 else 0

    out_probabilities.append(out_probability)

# Plot out probabilities
plt.bar(angle_ranges[:-1], out_probabilities, width=8, align='edge')
plt.xlabel('Launch Angle (degrees)')
plt.ylabel('Out Probability')
plt.title('Out Probability by Launch Angle')
plt.grid(which='both', linestyle='--', color='gray', alpha=0.5)
plt.show()


この続きはまた今度

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?