標準ライブラリで月ごとの売上を集計し、グラフ描画には matplotlib を使うのが定番です。CSVから「日付」と「金額」を読み込み、月単位に合計して折れ線グラフにすれば、売上推移を直感的に確認できます。
1. 必要なライブラリ
csv,pathlib,datetime(標準ライブラリ)matplotlib(グラフ描画用)
pip install matplotlib
2. サンプルCSV(sales.csv)
日付,商品,数量,金額
2025-11-01,りんご,10,3000
2025-11-01,みかん,5,2000
2025-12-02,りんご,7,2100
2025-12-15,みかん,12,4800
2026-01-03,バナナ,4,1200
3. Pythonコード例
import csv
from pathlib import Path
from collections import defaultdict
from datetime import datetime
import matplotlib.pyplot as plt
csv_path = Path.home() / "Documents" / "sales.csv"
# 月ごとの売上合計を集計
monthly_sales = defaultdict(int)
with csv_path.open("r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
date = datetime.strptime(row["日付"], "%Y-%m-%d")
month = date.strftime("%Y-%m") # "2025-11" のように月単位
monthly_sales[month] += int(row["金額"])
# 月順に並べ替え
months = sorted(monthly_sales.keys())
sales = [monthly_sales[m] for m in months]
# 折れ線グラフを描画
plt.figure(figsize=(8,5))
plt.plot(months, sales, marker="o", linestyle="-", color="tab:blue")
plt.title("月ごとの売上推移")
plt.xlabel("月")
plt.ylabel("売上金額(円)")
plt.grid(True)
plt.tight_layout()
plt.show()
Python4. 出力イメージ
- X軸:
2025-11,2025-12,2026-01 - Y軸:売上金額合計
- 折れ線グラフで月ごとの推移を表示
5. 応用ポイント
- 数量ベースで推移を見たい場合は「金額」ではなく「数量」を集計
- 商品ごとに色分けした折れ線を描けば比較が可能
- 棒グラフにすれば月ごとの売上規模を直感的に把握できる
まとめ
datetime.strptimeで日付を正規化し、strftime("%Y-%m")で月単位に集計matplotlibで折れ線グラフを描画- 応用すれば商品別・数量別・棒グラフなど多様な可視化が可能

