Matplotlibサンプルプログラム


Matplotlibのサンプル

(1)折れ線グラフ

import matplotlib.pyplot as plt
%matplotlib inline
price = [100, 250, 380, 500, 700]
number = [1, 2, 3, 4, 5]

plt.plot(price, number)
plt.title("price / number")
plt.xlabel("price")
plt.ylabel("number")
plt.show()

(2)ヒストグラム

import matplotlib.pyplot as plt
%matplotlib inline
# 平均50, 標準偏差10 の正規乱数を1,000件生成する
x = np.random.normal(50, 10, 1000)
plt.hist(x)

(3)散布図

import matplotlib.pyplot as plt
%matplotlib inline
# 乱数を生成
x = np.random.rand(100)
y = np.random.rand(100)
 
plt.scatter(x, y)

(4)グラフを横に二つ並べる

import matplotlib.pyplot as plt
%matplotlib inline

df2014 = pd.read_csv("data_2014_team_c.csv", encoding="cp932")
df2018 = pd.read_csv("data_2018_team_c.csv", encoding="cp932")

plt.subplots_adjust(wspace=0.4, hspace=0.1)
plt.figure(figsize=(10,5))

#1行2列でこのグラフが1番目
plt.subplot(1,2,1)
plt.title("2014")
plt.ylim(500, 750)
plt.plot(df2014["チーム"], df2014["失点"], label="失点")
plt.plot(df2014["チーム"], df2014["得点"], label="得点")
plt.legend()

#1行2列でこのグラフが2番目
plt.subplot(1,2,2)
plt.title("2018")
plt.ylim(500, 750)
plt.plot(df2018["チーム"], df2018["失点"], label="失点")
plt.plot(df2018["チーム"], df2018["得点"], label="得点")
plt.legend()

(5)二つのヒストグラムを同じグラフに重ねて書く

import matplotlib.pyplot as plt
%matplotlib inline

df_G = pd.read_csv("hitter_2020_G.csv", encoding="cp932")
df_Y = pd.read_csv("hitter_2020_YB.csv", encoding="cp932")
df_T = pd.read_csv("hitter_2020_T.csv", encoding="cp932")
df_C = pd.read_csv("hitter_2020_C.csv", encoding="cp932")
df_D = pd.read_csv("hitter_2020_D.csv", encoding="cp932")
df_S = pd.read_csv("hitter_2020_S.csv", encoding="cp932")

# 実績なしデータ(-)を削除
df_G2 = df_G.loc[df_G["OPS"] != "-", ["OPS","打席数"]].astype('float64')
df_Y2 = df_Y.loc[df_Y["OPS"] != "-", ["OPS","打席数"]].astype('float64')
df_T2 = df_T.loc[df_T["OPS"] != "-", ["OPS","打席数"]].astype('float64')
df_C2 = df_C.loc[df_C["OPS"] != "-", ["OPS","打席数"]].astype('float64')
df_D2 = df_D.loc[df_D["OPS"] != "-", ["OPS","打席数"]].astype('float64')
df_S2 = df_S.loc[df_S["OPS"] != "-", ["OPS","打席数"]].astype('float64')

# 打席数20超に限定
df_G3 = df_G2.loc[df_G2["打席数"] > 20, ["OPS"]].astype('float64')
df_Y3 = df_Y2.loc[df_Y2["打席数"] > 20, ["OPS"]].astype('float64')
df_T3 = df_T2.loc[df_T2["打席数"] > 20, ["OPS"]].astype('float64')
df_C3 = df_C2.loc[df_C2["打席数"] > 20, ["OPS"]].astype('float64')
df_D3 = df_D2.loc[df_D2["打席数"] > 20, ["OPS"]].astype('float64')
df_S3 = df_S2.loc[df_S2["打席数"] > 20, ["OPS"]].astype('float64')

plt.figure(figsize=(15,5))
plt.hist(df_G3["OPS"], alpha=0.5, label=["Giants"])
plt.hist([df_S3["OPS"]], alpha=0.3, label=["Swallows"])

plt.legend(loc="upper left", fontsize=13)