データの可視化とは
データの傾向やパターンを視覚的に確認するためにグラフを使います。Pythonでは matplotlib と seaborn がよく使われます。
python
import matplotlib.pyplot as pltimport matplotlibimport seaborn as snsimport numpy as npimport pandas as pd# 日本語フォントの設定(Colab用)matplotlib.rcParams["font.family"] = "IPAexGothic" # または DejaVu Sans折れ線グラフ
時系列データや連続した変化を表すのに使います。
python
import matplotlib.pyplot as pltimport numpy as npx = np.linspace(0, 2 * np.pi, 100)y = np.sin(x)plt.figure(figsize=(8, 4))plt.plot(x, y, label="sin(x)", color="blue", linewidth=2)plt.plot(x, np.cos(x), label="cos(x)", color="red", linestyle="--")plt.xlabel("x")plt.ylabel("y")plt.title("三角関数のグラフ")plt.legend()plt.grid(True)plt.tight_layout()plt.show()棒グラフ
カテゴリデータの比較に使います。
python
import matplotlib.pyplot as pltcategories = ["A", "B", "C", "D", "E"]values = [23, 45, 12, 67, 34]plt.figure(figsize=(8, 5))bars = plt.bar(categories, values, color=["#4C72B0", "#55A868", "#C44E52", "#8172B2", "#CCB974"])plt.xlabel("カテゴリ")plt.ylabel("値")plt.title("棒グラフの例")# 棒の上に値を表示for bar, val in zip(bars, values): plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5, str(val), ha="center", va="bottom")plt.tight_layout()plt.show()散布図
2つの変数の関係を視覚化するのに使います。
python
import matplotlib.pyplot as pltimport numpy as npnp.random.seed(42)x = np.random.randn(100)y = 2 * x + np.random.randn(100)plt.figure(figsize=(6, 6))plt.scatter(x, y, alpha=0.6, color="steelblue", edgecolors="white", linewidth=0.5)plt.xlabel("x")plt.ylabel("y")plt.title("散布図の例")# 回帰直線を追加coeffs = np.polyfit(x, y, 1)x_line = np.linspace(x.min(), x.max(), 100)plt.plot(x_line, np.polyval(coeffs, x_line), "r--", label="近似直線")plt.legend()plt.tight_layout()plt.show()ヒストグラム
データの分布を表すのに使います。
python
import matplotlib.pyplot as pltimport numpy as npdata = np.random.randn(1000)plt.figure(figsize=(8, 5))plt.hist(data, bins=30, color="steelblue", edgecolor="white", alpha=0.8)plt.xlabel("値")plt.ylabel("頻度")plt.title("正規分布のヒストグラム")plt.axvline(data.mean(), color="red", linestyle="--", label=f"平均: {data.mean():.2f}")plt.legend()plt.tight_layout()plt.show()seaborn(高レベルな可視化)
seabornはmatplotlibをベースにした統計的可視化ライブラリで、きれいなグラフが簡単に描けます。
python
import seaborn as snsimport pandas as pdimport matplotlib.pyplot as plt# アヤメデータセットiris = sns.load_dataset("iris")# ペアプロット(全変数の組み合わせ)sns.pairplot(iris, hue="species")plt.suptitle("アヤメデータセットのペアプロット", y=1.02)plt.show()# ボックスプロットplt.figure(figsize=(8, 5))sns.boxplot(data=iris, x="species", y="sepal_length")plt.title("品種別がく片の長さ")plt.show()練習: 売上グラフを作成
以下の月別売上データを使って棒グラフを作成してください。