04 — Matplotlib
Estimasi: 3 jam Tujuan: Plotting library standar Python. Wajib paham untuk EDA dan paper figure.
Kenapa Materi Ini Penting?
Tanpa visualisasi, data cuma deretan angka — dan otak manusia payah untuk pattern recognition di tabel besar. Matplotlib adalah fondasi semua plotting Python: seaborn, pandas plot, bahkan plotly fallback ke konsep matplotlib di bawahnya. Kalau kamu menguasai matplotlib, kamu bisa membuat plot apa saja untuk paper, presentasi, atau dashboard ML eksperimen.
Analogi: matplotlib = canvas pelukis. Kamu kontrol penuh atas tiap stroke kuas, warna, dan komposisi. Seaborn = pelukis dengan template "abstract", "potret", "landscape" — cantik default tapi customisasinya tetap pakai matplotlib di belakang. Saat kamu butuh figure untuk paper Dicoding final project atau tesis, matplotlib lah yang kamu pegang.
Di GenAI bootcamp nanti, kamu akan menggambar: loss curve training, attention heatmap, t-SNE embedding plot, distribusi token length, confusion matrix. Semua ini matplotlib (langsung atau lewat seaborn). Pastikan kamu paham hierarki Figure → Axes → Plot supaya tidak kebingungan saat plot tidak muncul atau tumpang tindih.
Hierarki Matplotlib: Figure, Axes, Plot
Cara Membaca Diagram:
- Node atas = Figure (kanvas keseluruhan).
- Dua node tengah = Axes (area plot di dalam figure, bisa lebih dari satu).
- Empat node bawah = isi tiap axes (line plot, scatter, title, labels, legend).
Walkthrough Step-by-Step:
- Buat Figure dengan
plt.subplots()atauplt.figure(). - Tambahkan satu atau banyak Axes (subplot) di dalamnya.
- Gambar konten di tiap Axes: line, scatter, bar, dll, plus label/legend.
Analogi Sehari-hari: album foto. Figure = halaman album, Axes = bingkai foto di halaman, Plot = isi foto di bingkai.
Diagram statis Mermaid sebagai fallback:
flowchart TD
F["Figure<br/>(kanvas keseluruhan)"] --> A1["Axes 1<br/>(satu plot area)"]
F --> A2["Axes 2<br/>(plot area kedua)"]
A1 --> P1["Line plot"]
A1 --> P2["Title, labels, legend"]
A2 --> P3["Scatter plot"]
A2 --> P4["Title, labels, legend"]
Analogi:
- Figure = halaman kertas kosong
- Axes = bingkai/kotak gambar di kertas itu (bisa lebih dari 1 = subplots)
- Plot = isi gambar di dalam kotak
Method yang sering dipanggil:
fig, ax = plt.subplots()— bikin figure + 1 axesfig, axes = plt.subplots(2, 2)— bikin figure + 4 axes (grid 2x2)ax.plot(...),ax.set_title(...)— gambar di axes
Bagian 1 — Plot Pertama
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show()
Style Cepat
plt.plot(x, y, color="red", linewidth=2, linestyle="--")
plt.plot(x, y, "r--") # shortcut
plt.plot(x, y, "b-o") # blue line dengan marker o
Multiple Plot
plt.plot(x, np.sin(x), label="sin")
plt.plot(x, np.cos(x), label="cos")
plt.legend()
plt.xlabel("x")
plt.ylabel("y")
plt.title("Sin and Cos")
plt.grid(True)
plt.show()
Bagian 2 — Object-Oriented API (Recommended)
Daripada plt.plot() style state-based:
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Title")
plt.show()
Lebih bersih untuk figure kompleks.
Bagian 3 — Subplots
# 2x2 grid
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
axes[0, 0].plot(x, np.sin(x))
axes[0, 0].set_title("sin")
axes[0, 1].plot(x, np.cos(x))
axes[0, 1].set_title("cos")
axes[1, 0].plot(x, np.exp(-x))
axes[1, 0].set_title("exp")
axes[1, 1].plot(x, x ** 2)
axes[1, 1].set_title("x^2")
plt.tight_layout()
plt.show()
Bagian 4 — Tipe Plot
Tabel Cepat: Pilih Plot yang Tepat
| Tujuan | Plot | Function |
|---|---|---|
| Trend over time | Line | ax.plot() |
| Hubungan 2 variabel numerik | Scatter | ax.scatter() |
| Bandingkan kategori | Bar | ax.bar() / ax.barh() |
| Distribusi 1 variabel | Histogram | ax.hist() |
| Distribusi + outlier | Box plot | ax.boxplot() |
| Matrix / korelasi | Heatmap | ax.imshow() |
| Komposisi (jarang) | Pie | ax.pie() |
Line Plot
ax.plot(x, y)
Scatter Plot
ax.scatter(x, y, s=20, c="blue", alpha=0.5)
Bar Chart
labels = ["A", "B", "C"]
values = [10, 25, 15]
ax.bar(labels, values)
ax.barh(labels, values) # horizontal
Histogram
data = np.random.randn(1000)
ax.hist(data, bins=50, edgecolor="black")
Box Plot
data = [np.random.randn(100) for _ in range(4)]
ax.boxplot(data, labels=["A", "B", "C", "D"])
Heatmap
matrix = np.random.randn(10, 10)
im = ax.imshow(matrix, cmap="viridis")
plt.colorbar(im)
Pie (jarang dipakai, kurang efektif)
ax.pie(values, labels=labels, autopct="%1.1f%%")
Bagian 5 — Customisasi
Limits, Ticks
ax.set_xlim(0, 10)
ax.set_ylim(-1, 1)
ax.set_xticks([0, 5, 10])
ax.set_xticklabels(["start", "mid", "end"])
ax.tick_params(rotation=45)
Color & Style
plt.style.use("ggplot") # atau "seaborn", "dark_background"
plt.rcParams["figure.figsize"] = (10, 6)
Annotation
ax.annotate("peak", xy=(np.pi/2, 1), xytext=(2, 1.2),
arrowprops=dict(arrowstyle="->"))
ax.text(5, 0, "midpoint", ha="center")
Save Figure
fig.savefig("plot.png", dpi=300, bbox_inches="tight")
fig.savefig("plot.pdf") # vector format
Bagian 6 — Plot dari Pandas
df = pd.DataFrame({
"x": np.arange(10),
"y1": np.random.randn(10).cumsum(),
"y2": np.random.randn(10).cumsum(),
})
df.plot(x="x") # auto plot all numeric
df.plot.bar()
df["y1"].hist()
df.plot.scatter(x="y1", y="y2")
Common Mistakes / FAQ
1. Plot Tidak Muncul
plt.plot(x, y)
# Lupa plt.show() di script Python (Jupyter auto-show)
plt.show()
Di Jupyter notebook biasanya otomatis muncul, tapi di script .py wajib plt.show().
2. Subplots Tumpang Tindih
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
# ... plot ...
plt.tight_layout() # auto-fix spacing!
plt.show()
3. Figure Lama Numpuk → Memory Leak
import matplotlib.pyplot as plt
for i in range(100):
fig, ax = plt.subplots()
ax.plot(data[i])
fig.savefig(f"plot_{i}.png")
plt.close(fig) # WAJIB close untuk loop besar!
4. Lupa figsize di Notebook → Plot Kekecilan
fig, ax = plt.subplots(figsize=(10, 6)) # lebar 10 inch, tinggi 6 inch
5. Mix plt.xxx dan ax.xxx
State-based (plt.) dan OO (ax.) bisa dicampur, tapi jangan. Pilih satu style. OO style (fig, ax = plt.subplots()) lebih recommended untuk figure kompleks.
6. Save Quality Rendah
fig.savefig("plot.png") # default 100 dpi, blur
fig.savefig("plot.png", dpi=300, bbox_inches="tight") # tajam, no whitespace
fig.savefig("plot.pdf") # vektor, infinite zoom
7. imshow Kebalik / Aspek Aneh
ax.imshow(matrix, cmap="viridis", aspect="auto")
# default aspect="equal" bikin kotak terlalu sempit kalau matrix non-square
Cek Pemahaman
- Bisa bikin line plot, scatter, bar, histogram?
- Bisa subplots 2x2?
- Bisa label, title, legend?
- Bisa save figure ke file?
Challenge 4.4
Challenge 1 — Distribusi Plot
Bikin figure 2×2:
- Histogram normal distribution (10000 sample)
- Histogram uniform
- Box plot 4 distribusi
- Scatter plot x vs y dengan correlation
Challenge 2 — Time Series
Dataset stock price (download CSV atau random walk):
- Plot harga over time
- Plot moving average 7-day, 30-day
- Annotate peak dan trough
Challenge 3 — Comparison Bar Chart
products = ["A", "B", "C", "D"]
sales_2025 = [100, 200, 150, 80]
sales_2026 = [120, 180, 200, 100]
Side-by-side bar chart untuk comparison. Pakai legend.
Challenge 4 — Loss Curve
Simulasi training:
epochs = np.arange(100)
train_loss = np.exp(-epochs * 0.05) + np.random.randn(100) * 0.05
val_loss = np.exp(-epochs * 0.04) + np.random.randn(100) * 0.05 + 0.1
Plot dengan label "Train" dan "Validation". Style: lines + markers.
Selanjutnya: 05-seaborn.md