# 【メモ】ダルビッシュ選手(2021年)の投球データ / Code **Published by:** [Shogaku](https://paragraph.com/@shogaku/) **Published on:** 2023-01-10 **URL:** https://paragraph.com/@shogaku/2021-code ## Content 昨日投稿のデータのコード備忘録記事 ダルビッシュ選手(2021年)の投球データ準備ダルビッシュ選手 ID 506433 https://baseballsavant.mlb.com/savant-player/yu-darvish-506433!pip install pybaseball from pybaseball import statcast df = statcast(start_dt='2021-04-01', end_dt='2021-12-31') df_darvish = df[df['pitcher'] == 506433] データdf_darvish['pitch_type'].value_counts() df_darvish['pitch_type'].value_counts().plot(kind='pie') import matplotlib.pyplot as plt # df_darvish DataFrame を月ごとにグループ分けする df_by_month = df_darvish.groupby(df_darvish['game_date'].dt.month) # 円グラフを描画する fig, ax = plt.subplots(nrows=1, ncols=len(df_by_month), figsize=(20, 10)) # 各月ごとの円グラフを描画する for i, (month, df_month) in enumerate(df_by_month): pitch_type_counts = df_month['pitch_type'].value_counts() ax[i].pie(pitch_type_counts, labels=pitch_type_counts.index, colors=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22']) ax[i].set_title(f"{month}") ax[i].legend(pitch_type_counts.index, title='ball') # 軸のラベルを非表示にする for i in range(len(df_by_month)): ax[i].set_ylabel('') # 凡例を非表示にする for i in range(len(df_by_month)): ax[i].legend().set_visible(False) import matplotlib.pyplot as plt # df_darvish DataFrame を月ごとにグループ分けする df_by_month = df_darvish.groupby(df_darvish['game_date'].dt.month) # 棒グラフを描画する fig, ax = plt.subplots(nrows=1, ncols=len(df_by_month), figsize=(20, 5)) # 各月ごとの棒グラフを描画する for i, (month, df_month) in enumerate(df_by_month): # 各月ごとの "pitch_type" カラムをカウントする pitch_type_counts = df_month['pitch_type'].value_counts() # 各月ごとの "pitch_type" カラムを棒グラフで表示する ax[i].bar(pitch_type_counts.index, pitch_type_counts.values, color=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22']) # 棒グラフのタイトルを設定する ax[i].set_title(f"{month}") # 棒グラフの軸に各球種を設定する ax[i].set_xticklabels(pitch_type_counts.index, rotation=45, ha='right') # 軸のラベルを非表示にする for i in range(len(df_by_month)): ax[i].set_ylabel('') # 凡例を非表示にする for i in range(len(df_by_month)): ax[i].legend().set_visible(False) import matplotlib.pyplot as plt # df_darvish DataFrame を月ごとにグループ分けする df_by_month = df_darvish.groupby(df_darvish['game_date'].dt.month) # 折れ線グラフを描画する fig, ax = plt.subplots(figsize=(10, 5)) # 各月ごとの "pitch_type" カラムをカウントする pitch_type_counts = df_by_month['pitch_type'].value_counts() # 各月ごとの "pitch_type" カラムを折れ線グラフで表示する # pitch_type_countsを月をインデックスとするデータフレームに変換する pitch_type_counts_df = pitch_type_counts.unstack(level=0) for pitch_type, pitch_type_count in pitch_type_counts_df.iteritems(): ax.plot(pitch_type_count.index, pitch_type_count.values, label=pitch_type) # 折れ線グラフのタイトルを設定する ax.set_title("Pitch type count by month") # 凡例を表示する ax.legend() # グラフを表示する plt.show()# import matplotlib.pyplot as plt # df_darvish DataFrame の "pitch_type" カラムをカウントする pitch_type_counts = df_darvish['pitch_type'].value_counts() # 棒グラフを描画する fig, ax = plt.subplots(figsize=(10, 5)) # 各月ごとの "pitch_type" カラムを棒グラフで表示する ax.bar(pitch_type_counts.index, pitch_type_counts.values) # 棒グラフのタイトルを設定する ax.set_title("Pitch type count") # 棒グラフの軸に各球種を設定する ax.set_xticklabels(pitch_type_counts.index, rotation=45) # 棒グラフを表示する plt.show() import pandas as pd # release_speedとspin rateの平均値を算出する df_mean = df_darvish.groupby('pitch_type')[['release_speed', 'release_spin_rate']].mean() # release_speedとspin rateの標準偏差を算出する df_std = df_darvish.groupby('pitch_type')[['release_speed', 'release_spin_rate']].std() # 平均値と標準偏差を行方向に結合する df_stats = pd.concat([df_mean, df_std], axis=1) df_stats.columns = ['mean_release_speed', 'mean_spin_rate', 'std_release_speed', 'std_spin_rate'] print(df_stats) print(df_darvish['pitch_type'].unique()) print(df['pitch_type'].unique()) ['CU' 'SL' 'FF' 'FS' 'FC' 'SI' 'KC' 'CH' 'CS']['FF' 'SL' 'CU' 'CH' 'FS' 'SI' 'KC' 'FC' 'CS' nan 'FA' 'KN' 'EP' 'SC']import matplotlib.pyplot as plt # ボックスプロットを描画する fig, ax = plt.subplots(figsize=(10, 5)) # 全投手のFFの球種のrelease_spin_rateをボックスプロットで表示する df[df['pitch_type'] == 'FF'].boxplot(column='release_spin_rate', by='pitch_type', ax=ax, positions=[1]) # ダルビッシュのFFの球種のrelease_spin_rateをボックスプロットで表示する df_darvish[df_darvish['pitch_type'] == 'FF'].boxplot(column='release_spin_rate', by='pitch_type', ax=ax, positions=[2]) # グラフのタイトルを設定する ax.set_title("release_spin_rate by pitch_type (all vs. Darvish)") # 軸のラベルを設定する ax.set_xlabel("FF_pitch_type") ax.set_ylabel("release_spin_rate") # X軸のラベルを設定する ax.set_xticklabels(['All', 'Darvish']) # グラフを表示する plt.show() import matplotlib.pyplot as plt # ボックスプロットを描画する fig, ax = plt.subplots(figsize=(10, 5)) # 全投手のFFの球種のrelease_spin_rateをボックスプロットで表示する df[df['pitch_type'] == 'FF'].boxplot(column='release_speed', by='pitch_type', ax=ax, positions=[1]) # ダルビッシュのFFの球種のrelease_spin_rateをボックスプロットで表示する df_darvish[df_darvish['pitch_type'] == 'FF'].boxplot(column='release_speed', by='pitch_type', ax=ax, positions=[2]) # 全投手のFFの球種のrelease_speedの平均値を表示する mean_all = df[df['pitch_type'] == 'FF']['release_speed'].mean() ax.text(1, mean_all, f"mean = {mean_all:.2f}", ha='center', va='bottom') # ダルビッシュのFFの球種のrelease_speedの平均値を表示する mean_darvish = df_darvish[df_darvish['pitch_type'] == 'FF']['release_speed'].mean() ax.text(2, mean_darvish, f"mean = {mean_darvish:.2f}", ha='center', va='bottom') # グラフのタイトルを設定する ax.set_title("release_speed by pitch_type (all vs. Darvish)") # 軸のラベルを設定する ax.set_xlabel("FF_pitch_type") ax.set_ylabel("release_speed") # X軸のラベルを設定する ax.set_xticklabels(['All', 'Darvish']) ax.set_ylim(70, 105) # グラフを表示する plt.show() import matplotlib.pyplot as plt # df_darvish DataFrame を月ごとにグループ分けする df_by_month = df_darvish.groupby(df_darvish['game_date'].dt.month) # 色を設定する colors = {'FC': '#1f77b4', 'SL': '#ff7f0e', 'FF': '#2ca02c', 'SI': '#d62728', 'FS': '#9467bd', 'CU': '#8c564b', 'KC': '#e377c2', 'CH': '#7f7f7f', 'CS': '#bcbd22'} # 棒グラフを描画する fig, ax = plt.subplots(nrows=1, ncols=len(df_by_month), figsize=(20, 5)) # 各月ごとの棒グラフを描画する for i, (month, df_month) in enumerate(df_by_month): # 各月ごとの "pitch_type" カラムをカウントする pitch_type_counts = df_month['pitch_type'].value_counts() # 各月ごとの "pitch_type" カラムを棒グラフで表示する ax[i].bar(pitch_type_counts.index, pitch_type_counts.values, color=[colors[x] for x in pitch_type_counts.index]) # 棒グラフのタイトルを設定する ax[i].set_title(f"{month}") # 棒グラフの軸に各球種を設定する ax[i].set_xticklabels(pitch_type_counts.index, rotation=45, ha='right') # 軸のラベルを非表示にする for i in range(len(df_by_month)): ax[i].set_ylabel('') # 凡例を非表示にする for i in range(len(df_by_month)): ax[i].legend().set_visible(False) # グラフを表示する plt.show() import matplotlib.pyplot as plt # df_darvish DataFrame を月ごとにグループ分けする df_by_month = df_darvish.groupby(df_darvish['game_date'].dt.month) # 円グラフを描画する fig, ax = plt.subplots(nrows=1, ncols=len(df_by_month), figsize=(20, 20)) # 各月ごとの円グラフを描画する for i, (month, df_month) in enumerate(df_by_month): # 各月ごとの "pitch_type" カラムをカウントする pitch_type_counts = df_month['pitch_type'].value_counts() # 各月ごとの "pitch_type" カラムを円グラフで表示する ax[i].pie(pitch_type_counts.values, labels=pitch_type_counts.index, colors=[colors[x] for x in pitch_type_counts.index]) # 円グラフのタイトルを設定する ax[i].set_title(f"{month}") # 棒グラフの軸に各球種を設定する ax[i].set_xticklabels(pitch_type_counts.index, rotation=45, ha='right') # 軸のラベルを非表示にする for i in range(len(df_by_month)): ax[i].set_ylabel('') # 凡例を非表示にする for i in range(len(df_by_month)): ax[i].legend().set_visible(False) # 平均値と標準偏差を行方向に結合する df_stats = pd.concat([df_mean, df_std], axis=1) df_stats.columns = ['release_speed 平均値', 'spin_rate 平均値', 'release_speed バラツキ', 'spin_rate バラツキ'] # 少数第二位までを表示するようにする df_stats = df_stats.round(2) # テーブルを表示する display(df_stats) # 平均値と標準偏差を行方向に結合する df_stats = pd.concat([df_mean, df_std], axis=1) # 列名を変更する df_stats.columns = ['mean_release_speed', 'mean_spin_rate', 'std_release_speed', 'std_spin_rate'] # 列を入れ替える df_stats = df_stats[['mean_release_speed', 'std_release_speed', 'mean_spin_rate', 'std_spin_rate']] # 少数第二位までを表示するようにする df_stats = df_stats.round(2) # テーブルを表示する display(df_stats) ## Publication Information - [Shogaku](https://paragraph.com/@shogaku/): Publication homepage - [All Posts](https://paragraph.com/@shogaku/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@shogaku): Subscribe to updates - [Twitter](https://twitter.com/ussu_ussu_ussu): Follow on Twitter