Skip to content

第 3 章 ソースコード一覧

書籍第 3 章「データ可視化」に掲載しているソースコードの一覧です。番号は書籍の「入力」番号と対応しています。上のバッジから、この章のコードをまとめた Google Colab ノートブックを開けます。

入力 3.1: Matplotlibのインポート

import matplotlib.pyplot as plt

入力 3.2: 日本語フォントの設定

!pip install matplotlib-fontja
import matplotlib_fontja

入力 3.3: グラフの基本要素の設定

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [1, 4, 9],
         label="すごい線")
plt.title("かっこいいグラフ")
plt.xlabel("横のラベル")
plt.ylabel("縦のラベル")
plt.grid(True)
plt.legend()
plt.show()

入力 3.4: fig, axスタイルによる描画

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9], label="線")
ax.set_title("タイトル")
ax.set_xlabel("横軸ラベル")
ax.set_ylabel("縦軸ラベル")
ax.legend()
ax.grid(True)
plt.show()

入力 3.5: 折れ線グラフの描画

import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4]
y = [0, 1, 4, 9, 16]
plt.plot(x, y)
plt.show()

入力 3.6: 棒グラフの描画

import matplotlib.pyplot as plt

plt.bar(["A", "B", "C", "D"], [5, 7, 3, 12])
plt.show()

入力 3.7: 散布図の描画

import matplotlib.pyplot as plt

plt.scatter([1, 3, 8, 5], [3, 6, 8, 4])
plt.show()

入力 3.8: ヒストグラムの描画

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randn(300)
plt.hist(data, bins=20, 
         color="skyblue", edgecolor="black")
plt.xlabel("値")
plt.ylabel("頻度")
plt.show()

入力 3.9: 箱ひげ図の描画

import matplotlib.pyplot as plt
import numpy as np

data = [np.random.randn(100), 
        np.random.randn(100)]

fig, ax = plt.subplots()
ax.boxplot(data, showmeans=True)
plt.show()

入力 3.10: ヒートマップの描画

import matplotlib.pyplot as plt
import numpy as np

matrix = np.random.rand(5, 5)

fig, ax = plt.subplots()
cax = ax.imshow(matrix)
fig.colorbar(cax)
plt.show()

入力 3.11: 1行2列のグラフ配置

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(100)
y1 = np.random.normal(100, 10, 100)
y2 = np.random.normal(80, 15, 100)
y3 = np.random.normal(60, 12, 100)
y4 = np.random.normal(45, 10, 100)

fig, axs = plt.subplots(1, 2, figsize=(5.8, 2.4), sharey=True)

axs[0].plot(x, y1, label="系列A")
axs[0].plot(x, y2, label="系列B")
axs[0].set_title("データセット1")
axs[0].set_xlabel("インデックス1")
axs[0].set_ylabel("値")
axs[0].legend()

axs[1].plot(x, y3, label="系列C")
axs[1].plot(x, y4, label="系列D")
axs[1].set_title("データセット2")
axs[1].set_xlabel("インデックス2")
axs[1].legend()

plt.tight_layout()
plt.show()

入力 3.12: 2行2列のグラフ配置

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
fig, axs = plt.subplots(2, 2, figsize=(5.8, 4.4))

axs[0, 0].plot(x, np.sin(x))
axs[0, 0].set_title("sin(x)")

axs[0, 1].plot(x, np.cos(x))
axs[0, 1].set_title("cos(x)")

axs[1, 0].plot(x, np.tan(x))
axs[1, 0].set_title("tan(x)")

axs[1, 1].plot(x, np.exp(-x))
axs[1, 1].set_title("exp(-x)")

plt.tight_layout()
plt.show()

入力 3.13: Seabornのインポート

import seaborn as sns

入力 3.14: サンプルデータセットの読み込み

import seaborn as sns

df = sns.load_dataset("penguins")
print(df.head())

入力 3.15: DataFrameの列の取り出し

# くちばしの長さの列だけを取り出す
print(df["bill_length_mm"].head())

入力 3.16: Seabornによる散布図の描画

import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset("penguins")
sns.set_theme(font="IPAexGothic")  # テーマを適用(日本語フォントを指定)

sns.scatterplot(data=df,
    x="bill_length_mm",
    y="body_mass_g",
    hue="species",
    style="sex"
)

plt.tight_layout()
plt.show()

入力 3.17: Irisデータセットの読み込み

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Iris データセットの読み込み(seaborn のサンプルデータ)
df = sns.load_dataset("iris")

print(df.shape)  # (行数, 列数)のタプルが表示される
print(df.head())

入力 3.18: ヒストグラムによる分布の確認

import matplotlib.pyplot as plt
import seaborn as sns

fig, axs = plt.subplots(2, 2, figsize=(7.2, 4.6))
feature_cols = ["sepal_length", "sepal_width", "petal_length", "petal_width"]

for i, ax in enumerate(axs.flatten()):
    sns.histplot(data=df, x=feature_cols[i], hue="species", kde=True, ax=ax)

plt.tight_layout()
plt.show()

入力 3.19: 箱ひげ図による分布の確認

import matplotlib.pyplot as plt
import seaborn as sns

fig, axs = plt.subplots(2, 2, figsize=(6.6, 4.6))
feature_cols = ["sepal_length", "sepal_width", "petal_length", "petal_width"]

for i, ax in enumerate(axs.flatten()):
    sns.boxplot(data=df, x="species", y=feature_cols[i], ax=ax)

plt.tight_layout()
plt.show()

入力 3.20: 箱ひげ図による外れ値の確認

import matplotlib.pyplot as plt
import seaborn as sns

plt.figure(figsize=(5.5, 2.8))
sns.boxplot(data=df[feature_cols])
plt.title("各特徴量の箱ひげ図")
plt.ylabel("値 (cm)")
plt.tight_layout()
plt.show()

入力 3.21: IQR法による外れ値の検出

# IQR法で外れ値を検出する
def detect_outliers_iqr(df, column):
    Q1 = df[column].quantile(0.25)
    Q3 = df[column].quantile(0.75)
    IQR = Q3 - Q1
    lower = Q1 - 1.5 * IQR
    upper = Q3 + 1.5 * IQR
    outliers = df[(df[column] < lower) | (df[column] > upper)]
    return outliers

# sepal_width の外れ値を検出
col = "sepal_width"
outliers = detect_outliers_iqr(df, col)
print(f"{col} の外れ値の数: {len(outliers)}")
print(outliers[[col, "species"]].head())

入力 3.22: 相関行列の計算

# 数値列のみで相関行列を計算
corr_matrix = df[feature_cols].corr()
print(corr_matrix.round(2))  # 値を小数第2位に丸めて表示

入力 3.23: 相関行列のヒートマップ表示

import matplotlib.pyplot as plt
import seaborn as sns

plt.figure(figsize=(6.3, 4.7))
sns.heatmap(corr_matrix, annot=True,
            fmt=".2f", cmap="coolwarm",
            center=0, square=True,
            linewidths=0.5)
plt.title("特徴量間の相関行列")
plt.tight_layout()
plt.show()

入力 3.24: ペアプロットの描画

import matplotlib.pyplot as plt
import seaborn as sns

sns.pairplot(df, hue="species", diag_kind="hist")
plt.tight_layout()
plt.show()