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?

Pythonでデータを可視化!Matplotlibを徹底解説

Last updated at Posted at 2025-09-30

目次

  1. はじめに
  2. Matplotlibとは?
  3. 基本的なグラフの描き方
  4. グラフのカスタマイズ
  5. 複数グラフの描画
  6. グラフの保存方法
  7. 応用例:データ可視化の実践
  8. まとめ

1. はじめに

データ分析や機械学習の結果を可視化する際、PythonではMatplotlibが最も基本的なライブラリのひとつです。
簡単な折れ線グラフから、複雑な散布図・ヒートマップまで幅広く対応できます。

この記事では、2dの時のMatplotlibの基本から応用までを分かりやすく解説します。


2. Matplotlibとは?

MatplotlibはPython用の2Dや3Dグラフ描画ライブラリです。
主要な特徴は以下の通り:

  • 折れ線グラフ、棒グラフ、散布図、円グラフなど様々なグラフを作成可能
  • グラフのタイトルやラベル、軸の範囲など自由にカスタマイズできる
  • NumPyPandasと組み合わせて使いやすい

まずはインストール方法です:

pip install matplotlib

3. 基本的なグラフの描き方

折れ線グラフ

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]

plt.plot(x, y)         # 折れ線グラフ
plt.title("折れ線グラフ")   # グラフタイトル
plt.xlabel("X軸")       # X軸ラベル
plt.ylabel("Y軸")       # Y軸ラベル
plt.show()             # グラフ表示

棒グラフ

categories = ["A", "B", "C", "D"]
values = [10, 20, 15, 25]

plt.bar(categories, values)
plt.title("棒グラフ")
plt.show()

散布図

x = [5, 7, 8, 7, 2, 17, 2]
y = [99, 86, 87, 88, 100, 86, 103]

plt.scatter(x, y)
plt.title("散布図")
plt.xlabel("X軸")
plt.ylabel("Y軸")
plt.show()

4. グラフのカスタマイズ

色・線のスタイル

plt.plot(x, y, color="red", linestyle="--", marker="o")

軸の範囲指定

plt.xlim(0, 10)
plt.ylim(0, 120)

グリッドの追加

plt.grid(True)

凡例の表示

plt.plot(x, y, label="データ1")
plt.plot(x, [i*2 for i in y], label="データ2")
plt.legend()

5. 複数グラフの描画

サブプロット

import numpy as np

x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

plt.subplot(2, 1, 1)  # 2行1列の1つ目
plt.plot(x, y1, color="blue")
plt.title("sin(x)")

plt.subplot(2, 1, 2)  # 2行1列の2つ目
plt.plot(x, y2, color="green")
plt.title("cos(x)")

plt.tight_layout()  # レイアウト調整
plt.show()

6. グラフの保存方法

plt.plot(x, y)
plt.savefig("graph.png")  # PNGとして保存
plt.savefig("graph.pdf")  # PDFとして保存

7. 応用例:データ可視化の実践

Pandasとの組み合わせ

import pandas as pd

data = pd.DataFrame({
    "日付": pd.date_range("2025-09-01", periods=7),
    "売上": [100, 120, 90, 150, 200, 170, 180]
})

plt.plot(data["日付"], data["売上"], marker="o")
plt.title("1週間の売上")
plt.xlabel("日付")
plt.ylabel("売上")
plt.xticks(rotation=45)  # 日付ラベルを傾ける
plt.grid(True)
plt.show()

8. まとめ

  • MatplotlibはPythonの基本的な可視化ライブラリ
  • 折れ線、棒グラフ、散布図など様々なグラフに対応
  • グラフの色、スタイル、軸、凡例など自由にカスタマイズ可能
  • PandasやNumPyと組み合わせるとデータ分析に強力

0
0
2

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?