Figure dan axes
Figure adalah seluruh gambar. Axes adalah satu plot di dalamnya, dan hampir setiap pemanggilan di bawah adalah method pada ax.
| Tugas | Kode |
|---|
| Mengimpor pyplot | import matplotlib.pyplot as plt |
| Satu figure dengan satu plot | fig, ax = plt.subplots() |
| Mengatur ukuran dalam inci | fig, ax = plt.subplots(figsize=(8, 4)) |
| Menggambar pada axes | ax.plot(x, y) |
| Menampilkan figure | plt.show() |
| Menyimpan sebagai PNG yang tajam | fig.savefig("chart.png", dpi=150, bbox_inches="tight") |
| Menyimpan sebagai grafik vektor | fig.savefig("chart.svg"), fig.savefig("chart.pdf") |
| Latar belakang transparan | fig.savefig("chart.png", transparent=True) |
| Menutup figure untuk membebaskan memori | plt.close(fig) |
| Gaya pyplot cepat untuk satu grafik | plt.plot(x, y)
plt.title("Quick look")
plt.show() |
Jenis plot
| Tugas | Kode |
|---|
| Grafik garis | ax.plot(x, y) |
| Scatter plot | ax.scatter(x, y, s=20, alpha=0.7) |
| Scatter diwarnai berdasarkan nilai, dengan color bar | points = ax.scatter(x, y, c=y, cmap="viridis")
fig.colorbar(points, ax=ax) |
| Grafik batang | ax.bar(cats, a) |
| Grafik batang horizontal | ax.barh(cats, a) |
| Batang bertumpuk | ax.bar(cats, a, label="2025")
ax.bar(cats, b, bottom=a, label="2026") |
| Batang berkelompok | pos = np.arange(len(cats))
ax.bar(pos - 0.2, a, width=0.4)
ax.bar(pos + 0.2, b, width=0.4)
ax.set_xticks(pos, labels=cats) |
| Histogram | ax.hist(data, bins=30) |
| Box plot | ax.boxplot([data, data * 2], tick_labels=["A", "B"]) |
| Violin plot | ax.violinplot([data, data * 2]) |
| Diagram lingkaran (pie) | ax.pie([40, 35, 25], labels=cats, autopct="%1.0f%%") |
| Area di antara dua kurva | ax.fill_between(x, y - 0.2, y + 0.2, alpha=0.3) |
| Error bar | ax.errorbar([1, 2, 3], [4, 5, 3], yerr=[0.5, 0.3, 0.6], fmt="o", capsize=4) |
| Grafik tangga (step) | ax.step(x, y, where="mid") |
| Heatmap dari array 2D | image = ax.imshow(np.random.default_rng(0).random((5, 5)), cmap="magma")
fig.colorbar(image, ax=ax) |
| Contour plot terisi | X, Y = np.meshgrid(x, x)
ax.contourf(X, Y, np.sin(X) * np.cos(Y), levels=20) |
| Kepadatan banyak titik | ax.hexbin(data, data + np.random.default_rng(1).normal(size=200), gridsize=20) |
| Garis acuan horizontal atau vertikal | ax.axhline(0, color="gray", linestyle="--"), ax.axvline(5) |
| Mengarsir sebuah rentang | ax.axvspan(2, 4, alpha=0.2) |
Garis, marker dan warna
| Tugas | Kode |
|---|
| Warna, ketebalan, dan gaya garis | ax.plot(x, y, color="tab:red", linewidth=2, linestyle="--") |
| Marker pada titik | ax.plot(x, y, marker="o", markersize=4) |
| String format singkat | ax.plot(x, y, "g--o") |
| Transparansi | ax.plot(x, y, alpha=0.5) |
| Gaya garis | "-", "--", "-.", ":" |
| Kode marker | "o", "s", "^", "x", ".", "*" |
| Cara menyebut warna | "tab:blue", "C1", "#1f77b4", (0.2, 0.4, 0.6) |
| n warna dari sebuah colormap | colors = plt.colormaps["viridis"](np.linspace(0, 1, 5)) |
| Siklus warnamu sendiri | ax.set_prop_cycle(color=["#0b7285", "#e8590c", "#5f3dc4"]) |
| Batang dengan garis tepi dan arsiran | ax.bar(cats, a, color="white", edgecolor="black", hatch="//") |
Judul, label dan legend
| Tugas | Kode |
|---|
| Judul dan label sumbu | ax.set_title("Sales"), ax.set_xlabel("Month"), ax.set_ylabel("EUR") |
| Semuanya dalam satu pemanggilan | ax.set(title="Sales", xlabel="Month", ylabel="EUR") |
| Legend dari label garis | ax.plot(x, y, label="sin")
ax.legend() |
| Posisi dan jumlah kolom legend | ax.legend(loc="upper right", ncols=2, frameon=False) |
| Legend di luar plot | ax.legend(loc="center left", bbox_to_anchor=(1, 0.5)) |
| Teks di posisi data | ax.text(5, 0.5, "note") |
| Anotasi dengan panah | ax.annotate("peak", xy=(1.57, 1), xytext=(3, 1.2), arrowprops=dict(arrowstyle="->")) |
| Label nilai pada batang | bars = ax.bar(cats, a)
ax.bar_label(bars) |
| Judul untuk seluruh figure | fig.suptitle("Q1 report") |
| Matematika di dalam label | ax.set_xlabel(r"$\alpha$ (rad)") |
Axes, tick dan skala
| Tugas | Kode |
|---|
| Batas sumbu | ax.set_xlim(0, 10), ax.set_ylim(bottom=0) |
| Skala logaritmik | ax.set_yscale("log") |
| Memilih tick dan labelnya | ax.set_xticks([0, 5, 10], labels=["start", "middle", "end"]) |
| Memutar label tick | ax.tick_params(axis="x", labelrotation=45) |
| Garis grid | ax.grid(True, alpha=0.3) |
| Sumbu persen | from matplotlib.ticker import PercentFormatter
ax.yaxis.set_major_formatter(PercentFormatter(1.0)) |
| Pemisah ribuan | ax.yaxis.set_major_formatter("{x:,.0f}") |
| Menyembunyikan batas atas dan kanan | ax.spines[["top", "right"]].set_visible(False) |
| Sumbu y kedua di sebelah kanan | ax2 = ax.twinx()
ax2.plot(x, y * 100, color="tab:orange") |
| Skala yang sama di kedua sumbu | ax.set_aspect("equal") |
| Membalik sumbu | ax.invert_yaxis() |
| Menyembunyikan axes sepenuhnya | ax.axis("off") |
| Label tanggal yang mudah dibaca | fig.autofmt_xdate() |
Subplot dan tata letak
plt.subplots(rows, cols) mengembalikan array NumPy berisi axes. Akses dengan indeks seperti array.
| Tugas | Kode |
|---|
| Grid berisi plot | fig, axs = plt.subplots(2, 2, figsize=(8, 6)) |
| Menggambar di salah satunya | axs[0, 1].plot(x, y) |
| Perulangan atas semuanya | for ax in axs.flat:
ax.grid(True) |
| Berbagi sumbu antar-plot | fig, axs = plt.subplots(1, 3, sharey=True) |
| Jarak yang mencegah tumpang tindih | fig, axs = plt.subplots(2, 2, layout="constrained") |
| Memperbaiki tumpang tindih setelah menggambar | fig.tight_layout() |
| Kolom dengan lebar berbeda | fig, axs = plt.subplots(1, 2, width_ratios=[3, 1]) |
| Tata letak bernama dengan panel lebar | fig, axd = plt.subplot_mosaic([["top", "top"], ["left", "right"]])
axd["top"].plot(x, y) |
| Plot kecil di dalam plot | inset = ax.inset_axes([0.6, 0.6, 0.35, 0.35]) |
| Menyembunyikan panel kosong | axs[0].axis("off") |
Style dan default
| Tugas | Kode |
|---|
| Memakai style bawaan | plt.style.use("ggplot") |
| Menampilkan daftar style | plt.style.available |
| Tampilan ala Seaborn tanpa seaborn | plt.style.use("seaborn-v0_8-whitegrid") |
| Style untuk satu figure saja | with plt.style.context("dark_background"):
fig, ax = plt.subplots() |
| Ukuran font default | plt.rcParams["font.size"] = 12 |
| Ukuran dan resolusi figure default | plt.rcParams["figure.figsize"] = (8, 4), plt.rcParams["figure.dpi"] = 120 |
| Kembali ke default | plt.style.use("default") |
| Colormap umum: sequential, diverging, abu-abu | "viridis", "coolwarm", "Greys" |
Plot dari pandas
pandas membuat plot dengan Matplotlib. Kirim ax= untuk menggambar di axes milikmu, atau simpan ax yang dikembalikan pandas.
| Tugas | Kode |
|---|
| Kolom DataFrame ke axes milikmu | df.plot(x="month", y="sales", ax=ax) |
| Grafik batang dari ringkasan per kelompok | df.groupby("city")["sales"].sum().plot.bar(ax=ax) |
| Melanjutkan styling pada hasil gambar pandas | ax = df.plot(x="month", y="sales")
ax.set_title("Sales") |
| Kolom langsung ke Matplotlib | ax.plot(df["month"], df["sales"]) |
Matplotlib 3.11: bentuk lama dan yang ditulis sekarang
Kode yang disalin dari tutorial lama bisa gagal atau memunculkan peringatan di Matplotlib 3.11. Tulis bentuk di kolom Matplotlib 3.11 sebagai gantinya.
| Tugas | Matplotlib 3.11 | Bentuk lama |
|---|
| Label box plot | ax.boxplot([data, data * 2], tick_labels=["A", "B"]) | labels=["A", "B"] |
| Box plot atau violin plot horizontal | ax.boxplot(data, orientation="horizontal") | vert=False |
| Mengambil colormap | plt.colormaps["viridis"] | plt.cm.get_cmap("viridis") |
| Style Seaborn | plt.style.use("seaborn-v0_8") | plt.style.use("seaborn") |
Kode Matplotlib yang kamu butuhkan untuk mengubah data menjadi grafik yang jelas, dikelompokkan per tugas: figure dan axes, jenis plot, garis dan warna, judul dan legend, axes dan tick, subplot dan tata letak, style, serta membuat plot dari pandas. Setiap baris berisi potongan kode singkat yang bisa kamu tempel, plus satu kalimat tentang kegunaannya.
Semua yang ada di sini memakai gaya berorientasi objek (fig, ax = plt.subplots(), lalu method pada ax) dan ditulis untuk Matplotlib 3.11, versi yang dijalankan Coddy. Bentuk lama seperti labels= di boxplot hanya muncul di tabel terakhir, di samping apa yang sebaiknya ditulis sekarang. Contoh-contohnya memakai x = np.linspace(0, 10, 50), y = np.sin(x), dan sampel nilai normal bernama data. Baru mengenal Python? Mulailah dari cheat sheet Python, dan simpan juga cheat sheet pandas, NumPy, dan scikit-learn di samping halaman ini.