# Referensi Cepat Matplotlib

*Figure, axes, plot, dan kustomisasi*

> Source: Matplotlib Documentation (matplotlib.org) · MIT

## Plot Dasar

### Line Plot

```
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 8, 3]
plt.plot(x, y)
plt.show()
```

### Pintasan Plot Cepat

```
plt.plot(y)              # x auto 0..N-1
plt.plot(x, y, "ro--")  # red circles, dashed
plt.plot(x, y, "bs-")   # blue squares, solid
```

### Kode Format String

| Command | Description |
|---------|-------------|
| ``r` `g` `b` `k`` | Merah, hijau, biru, hitam |
| ``o` `s` `^` `D`` | Marker lingkaran, kotak, segitiga, berlian |
| ``-` `--` `-.` `:`` | Garis solid, putus-putus, titik-putus, titik-titik |

## Subplot

### Figure dan Axes

```
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title("Single Plot")
plt.show()
```

### Grid Subplot

```
fig, axes = plt.subplots(2, 2, figsize=(8, 6))
axes[0, 0].plot(x, y)
axes[0, 1].bar(x, y)
axes[1, 0].scatter(x, y)
fig.tight_layout()
```

### Axes Berbagi

```
fig, (ax1, ax2) = plt.subplots(1, 2,
    sharey=True, figsize=(10, 4))
ax1.plot(x, y)
ax2.plot(x, y2)
```

## Label & Judul

### Label Sumbu dan Judul

```
plt.plot(x, y)
plt.xlabel("Time (s)")
plt.ylabel("Value")
plt.title("Sensor Reading")
plt.show()
```

### Label Gaya OO

```
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlabel("X"); ax.set_ylabel("Y")
ax.set_title("My Plot")
```

### Anotasi

```
ax.annotate("Peak", xy=(4, 8),
    xytext=(3, 9),
    arrowprops=dict(arrowstyle="->"))
```

## Kustomisasi

### Warna dan Gaya

```
plt.plot(x, y, color="#FF5733",
    linewidth=2, linestyle="--")
plt.plot(x, y2, color="steelblue",
    marker="o", markersize=5)
```

### Ukuran Figure dan DPI

```
fig, ax = plt.subplots(figsize=(10, 6), dpi=100)
plt.rcParams["figure.figsize"] = (8, 5)
```

### Lembar Gaya

```
print(plt.style.available)  # list all
plt.style.use("seaborn-v0_8")
plt.style.use("ggplot")
```

## Batang & Histogram

### Diagram Batang

```
labels = ["A", "B", "C", "D"]
values = [23, 45, 12, 37]
plt.bar(labels, values, color="teal")
plt.show()
```

### Batang Berkelompok / Bertumpuk

```
import numpy as np
x = np.arange(4); w = 0.35
plt.bar(x - w/2, v1, w, label="2024")
plt.bar(x + w/2, v2, w, label="2025")
plt.xticks(x, labels)
```

### Histogram

```
data = np.random.randn(1000)
plt.hist(data, bins=30, edgecolor="black",
    alpha=0.7)
plt.show()
```

## Sebar & Garis

### Plot Sebar

```
plt.scatter(x, y, c="red", s=50,
    alpha=0.6, edgecolors="black")
plt.show()
```

### Sebar dengan Colormap

```
sc = plt.scatter(x, y, c=values,
    cmap="viridis", s=sizes)
plt.colorbar(sc, label="Intensity")
```

### Beberapa Garis

```
plt.plot(x, y1, label="Train")
plt.plot(x, y2, label="Validation")
plt.legend()
plt.show()
```

## Axes & Tanda Sumbu

### Batas dan Skala Sumbu

```
ax.set_xlim(0, 10)
ax.set_ylim(-1, 1)
ax.set_xscale("log")
ax.set_yscale("log")
```

### Tanda Sumbu Custom

```
ax.set_xticks([0, 1, 2, 3, 4])
ax.set_xticklabels(["Mon", "Tue", "Wed",
    "Thu", "Fri"], rotation=45)
```

### Grid

```
ax.grid(True, linestyle="--", alpha=0.5)
ax.grid(axis="y")  # horizontal only
```

## Legenda

### Menambahkan Legenda

```
ax.plot(x, y, label="Series A")
ax.plot(x, y2, label="Series B")
ax.legend(loc="upper right")
```

### Penempatan Legenda

| Command | Description |
|---------|-------------|
| ``'best'`` | Posisi terbaik otomatis (default) |
| ``'upper left'`` | Pojok kiri atas |
| ``'lower right'`` | Pojok kanan bawah |
| ``'center'`` | Tengah axes |
| ``bbox_to_anchor=(1, 1)`` | Tempatkan di luar area axes |

### Kustomisasi Legenda

```
ax.legend(fontsize=8, frameon=False,
    ncol=2, title="Legend")
```

## Menyimpan

### Simpan ke File

```
plt.savefig("plot.png", dpi=300,
    bbox_inches="tight")
plt.savefig("plot.pdf")
plt.savefig("plot.svg", transparent=True)
```

### Format yang Didukung

| Command | Description |
|---------|-------------|
| `PNG` | Raster, terbaik untuk web/layar |
| `PDF` | Vektor, terbaik untuk cetak/makalah |
| `SVG` | Vektor, skalabel untuk web |
| `EPS` | Vektor, jurnal ilmiah lama |

### Simpan dari Objek Figure

```
fig, ax = plt.subplots()
ax.plot(x, y)
fig.savefig("output.png", dpi=150,
    facecolor="white")
```

## Pola Umum

### Twin Axes (Dua Skala Y)

```
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, temp, "r-", label="Temp")
ax2.plot(x, pressure, "b-", label="Pressure")
```

### Fill Between

```
ax.fill_between(x, y_low, y_high,
    alpha=0.3, color="blue")
```

### Heatmap dengan imshow

```
data = np.random.rand(10, 10)
plt.imshow(data, cmap="hot",
    interpolation="nearest")
plt.colorbar()
```

### Diagram Lingkaran

```
plt.pie(sizes, labels=labels,
    autopct="%1.1f%%", startangle=90)
plt.axis("equal")
```
