Python Matplotlib

 # Matplotlib — Python's core plotting library

# import convention: import matplotlib.pyplot as plt
# plt.show() displays the plot; plt.savefig() saves it to a file

import matplotlib.pyplot as plt
import numpy as np

# ══════════════════════════════════════════════════════════════════════════════
# ── 1. Basic Line Plot ────────────────────────────────────────────────────────
# plt.plot(x, y) — draws a line connecting (x,y) points
# ══════════════════════════════════════════════════════════════════════════════

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y) # draws line through points
plt.title("Basic Line Plot") # title at top of plot
plt.xlabel("X Axis") # label for x-axis
plt.ylabel("Y Axis") # label for y-axis
plt.show() # displays the plot # Output: straight diagonal line from (1,2) to (5,10)

# ══════════════════════════════════════════════════════════════════════════════
# ── 2. Styling a Line Plot ────────────────────────────────────────────────────
# color, linestyle, linewidth, marker control the appearance
# ══════════════════════════════════════════════════════════════════════════════

plt.plot(x, y,
color="red", # line color
linestyle="--", # dashed line (- solid, -- dashed, : dotted, -. dashdot)
linewidth=2, # thickness of line
marker="o", # dot at each data point (o circle, s square, ^ triangle)
markersize=8, # size of marker
label="Growth") # legend label

plt.title("Styled Line Plot")
plt.legend() # plt.legend() — shows labels defined in plot()
plt.grid(True) # plt.grid() — adds background grid lines
plt.show() # Output: red dashed line with circles at each point, grid visible

# ══════════════════════════════════════════════════════════════════════════════
# ── 3. Multiple Lines on Same Plot ───────────────────────────────────────────
# call plt.plot() multiple times before plt.show()
# ══════════════════════════════════════════════════════════════════════════════

x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25] # y = x²
y2 = [1, 2, 3, 4, 5] # y = x

plt.plot(x, y1, label="x²", color="blue")
plt.plot(x, y2, label="x", color="orange", linestyle="--")
plt.title("Multiple Lines")
plt.legend() # shows both labels in a box
plt.show() # Output: two lines on same axes — one curved (x²), one straight (x)
plt.grid(True)
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")


# ══════════════════════════════════════════════════════════════════════════════
# ── 4. Bar Chart ──────────────────────────────────────────────────────────────
# plt.bar(x, height) — vertical bars; plt.barh() for horizontal
# ══════════════════════════════════════════════════════════════════════════════

categories = ["HR", "IT", "Finance", "Marketing"]
values = [52000, 85000, 72000, 63000]

plt.bar(categories, values,
color=["#4caf50","#2196f3","#ff9800","#e91e63"], # one color per bar
edgecolor="black", # border color of each bar
width=0.5) # bar width (default 0.8)

plt.title("Average Salary by Department")
plt.ylabel("Salary ($)")
plt.show() # Output: 4 colored vertical bars, tallest for IT

# ── Horizontal bar chart ──────────────────────────────────────────────────────
plt.barh(categories, values, color="steelblue") # plt.barh() flips bars horizontal
plt.title("Horizontal Bar Chart")
plt.xlabel("Salary ($)")
plt.show() # Output: same data as horizontal bars — useful when labels are long
# ══════════════════════════════════════════════════════════════════════════════
# ── 5. Scatter Plot ───────────────────────────────────────────────────────────
# plt.scatter(x, y) — plots individual points; shows relationship between variables
# ══════════════════════════════════════════════════════════════════════════════

np.random.seed(42)
x = np.random.randint(20, 60, 50) # 50 random ages
y = x * 1500 + np.random.randint(-5000, 5000, 50) # salary loosely based on age

plt.scatter(x, y,
color="purple", # dot color
alpha=0.6, # transparency (0=invisible, 1=solid)
s=60, # dot size
edgecolors="black", # dot border color
linewidths=0.5)

plt.title("Age vs Salary")
plt.xlabel("Age")
plt.ylabel("Salary")
plt.show() # Output: scattered purple dots showing positive correlation

# ══════════════════════════════════════════════════════════════════════════════
# ── 6. Histogram ──────────────────────────────────────────────────────────────
# plt.hist(data, bins) — shows distribution/frequency of data
# ══════════════════════════════════════════════════════════════════════════════

data = np.random.randn(1000) # 1000 standard normal values

plt.hist(data,
bins=30, # number of buckets/intervals
color="teal",
edgecolor="white", # border between bars
alpha=0.8)

plt.title("Normal Distribution Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show() # Output: bell-shaped histogram — most values near 0, fewer at extremes

# ══════════════════════════════════════════════════════════════════════════════
# ── 7. Pie Chart ──────────────────────────────────────────────────────────────
# plt.pie(values) — shows proportions as slices of a circle
# ══════════════════════════════════════════════════════════════════════════════

sizes = [35, 25, 20, 20]
labels = ["Python", "Java", "C++", "Other"]
colors = ["#4caf50", "#2196f3", "#ff9800", "#9c27b0"]

plt.pie(sizes,
labels=labels,
colors=colors,
autopct="%1.1f%%", # autopct — shows % value on each slice
startangle=90, # rotate chart so first slice starts at top
explode=[0.1,0,0,0]) # explode — pulls out first slice slightly

plt.title("Programming Language Usage")
plt.show() # Output: pie chart with Python slice pulled out, percentages shown

# ══════════════════════════════════════════════════════════════════════════════
# ── 8. Figure & Axes — OOP Style ─────────────────────────────────────────────
# Preferred for complex plots — more control than plt.plot() directly
# fig = the window/canvas; ax = the single plot area inside it
# ══════════════════════════════════════════════════════════════════════════════

fig, ax = plt.subplots(figsize=(8, 4)) # figsize=(width, height) in inches; default (6.4, 4.8)

x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [2, 3, 5, 7, 11]

ax.plot(x, y1, label="Line A", color="blue")
ax.plot(x, y2, label="Line B", color="red", linestyle="--")

ax.set_title("Two Lines") # title at top
ax.set_xlabel("X values") # x-axis label
ax.set_ylabel("Y values") # y-axis label
ax.set_xlim(1, 5) # set_xlim — x-axis range
ax.set_ylim(0, 30) # set_ylim — y-axis range
ax.legend() # shows Line A / Line B labels
ax.grid(True) # adds grid lines

plt.show() # Output: two lines with labels, title, legend, and grid

# ══════════════════════════════════════════════════════════════════════════════
# ── 9. Subplots Grid ──────────────────────────────────────────────────────────
# plt.subplots(rows, cols) — creates a grid of multiple plots
#
# Grid layout for plt.subplots(2, 2):
# axes[0,0] | axes[0,1] ← row 0
# ──────────┼──────────
# axes[1,0] | axes[1,1] ← row 1
# ══════════════════════════════════════════════════════════════════════════════

fig, axes = plt.subplots(2, 2, figsize=(10, 8))

axes[0, 0].plot([1, 2, 3, 4], [1, 4, 2, 3], color="blue")
axes[0, 0].set_title("Line Chart")

axes[0, 1].bar(["A", "B", "C"], [5, 3, 7], color="orange")
axes[0, 1].set_title("Bar Chart")

axes[1, 0].scatter([1, 2, 3, 4], [4, 2, 3, 1], color="green")
axes[1, 0].set_title("Scatter Plot")

axes[1, 1].plot([1, 2, 3, 4], [1, 8, 27, 64], color="red", linestyle="--")
axes[1, 1].set_title("Curved Line")

plt.suptitle("2×2 Grid of Plots", fontsize=14) # title for the whole figure
plt.tight_layout() # prevent plots from overlapping
plt.show() # Output: 4 plots in a 2×2 grid

# ══════════════════════════════════════════════════════════════════════════════
# ── 10. Multiple Plot Types using ax Objects ──────────────────────────────────
# Unpack axes directly when the layout is a single row or small fixed count
# ══════════════════════════════════════════════════════════════════════════════

fig, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4, figsize=(16, 4))
# Unpacks 4 axes directly into ax1, ax2, ax3, ax4

ax1.plot([1, 2, 3, 4], [1, 4, 2, 3], color="blue", marker="o")
ax1.set_title("Line Plot")
ax1.set_xlabel("X")
ax1.set_ylabel("Y")

ax2.bar(["HR", "IT", "Finance"], [50000, 80000, 65000], color="orange")
ax2.set_title("Bar Chart")
ax2.set_xlabel("Dept")
ax2.set_ylabel("Salary")

ax3.scatter([1, 2, 3, 4, 5], [5, 3, 4, 1, 2], color="green", s=80)
ax3.set_title("Scatter Plot")
ax3.set_xlabel("X")
ax3.set_ylabel("Y")

ax4.hist([1, 2, 2, 3, 3, 3, 4, 4, 5], bins=5, color="purple", edgecolor="white")
ax4.set_title("Histogram")
ax4.set_xlabel("Value")
ax4.set_ylabel("Frequency")

plt.suptitle("4 Different Plot Types using ax", fontsize=13)
plt.tight_layout()
plt.show() # Output: 4 side-by-side plots — line, bar, scatter, histogram


# ── Key pattern summary ───────────────────────────────────────────────────────
# fig, ax = plt.subplots() → 1 plot
# fig, (ax1, ax2) = plt.subplots(1, 2) → 2 side-by-side, unpack directly
# fig, axes = plt.subplots(2, 3) → 6 plots, access via axes[row, col]
# each ax is independent — ax1.plot() does NOT affect ax2

# ══════════════════════════════════════════════════════════════════════════════
# ── 11. Customizing Ticks ─────────────────────────────────────────────────────
# Control what values and labels appear on each axis
# ══════════════════════════════════════════════════════════════════════════════

fig, ax = plt.subplots()
x = [1, 2, 3, 4, 5]
ax.plot(x, [10, 25, 15, 30, 20])

ax.set_xlim(0.5, 5.5) # set xlim FIRST before ticks
ax.set_xticks([1, 2, 3, 4, 5]) # set_xticks — positions of ticks
ax.set_xticklabels(["Mon","Tue","Wed","Thu","Fri"]) # set_xticklabels — tick labels
ax.set_yticks([0, 10, 20, 30])
plt.title("Weekly Values")
plt.show() # Output: x-axis shows Mon-Fri instead of 1-5

# ══════════════════════════════════════════════════════════════════════════════
# ── 12. Annotations ───────────────────────────────────────────────────────────
# ax.annotate() — add text with an arrow pointing to a data point
# ax.text() — add plain text at a position
# ══════════════════════════════════════════════════════════════════════════════

fig, ax = plt.subplots()
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 6, 3]
ax.plot(x, y, marker="o")

ax.annotate("Peak", # text to display
xy=(4, 6), # point to point at (arrow tip)
xytext=(3.5, 5.5), # where text is placed
arrowprops={"arrowstyle":"->"}) # arrow style

ax.text(1, 2.2, "Start", fontsize=9, color="gray") # plain text at (1, 2.2)
plt.title("Annotated Plot")
plt.show() # Output: line with "Peak" annotation arrow and "Start" text label

# ══════════════════════════════════════════════════════════════════════════════
# ── 13. plt.figure() and fig.add_axes() ──────────────────────────────────────
# plt.figure() — creates a blank canvas with full control over size and resolution
# fig.add_axes([l, b, w, h]) — places an axes at a custom position (fractions 0.0–1.0)
# ══════════════════════════════════════════════════════════════════════════════

# ── plt.figure() with fig.add_subplot() — manual grid layout ─────────────────
# plt.figure() → blank canvas, add axes manually with fig.add_subplot()
# plt.subplots(r,c) → canvas + axes grid in one call (more common)

fig = plt.figure(figsize=(10, 4)) # figsize=(w, h) in inches; dpi= sets resolution

ax1 = fig.add_subplot(1, 2, 1) # (rows, cols, index) → 1 row, 2 cols, 1st plot
ax1.plot([1,2,3], [1,4,9])
ax1.set_title("Left Plot")

ax2 = fig.add_subplot(1, 2, 2) # 1 row, 2 cols, 2nd plot
ax2.bar(["A","B","C"], [3,7,5])
ax2.set_title("Right Plot")

plt.tight_layout()
plt.show() # Output: two side-by-side plots — line chart and bar chart

# ── fig.add_axes() — inset plot inside a larger plot ─────────────────────────
# fig.add_axes([left, bottom, width, height]) — all values are fractions (0.0 to 1.0)
# left → distance from left edge (0.0 = left, 1.0 = right)
# bottom → distance from bottom edge (0.0 = bottom, 1.0 = top)

fig = plt.figure(figsize=(8, 5))

ax_main = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # 10% margin, 80% wide/tall
ax_main.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25], color="blue")
ax_main.set_title("Main Plot with Inset")

ax_inset = fig.add_axes([0.15, 0.55, 0.3, 0.3]) # small box inside main
ax_inset.plot([1, 2, 3], [3, 1, 2], color="red")
ax_inset.set_title("Inset", fontsize=9)
ax_inset.tick_params(labelsize=7)

plt.show() # Output: main blue line plot with a small red inset plot inside it


# ── add_axes vs add_subplot vs subplots ───────────────────────────────────────
# fig.add_axes([l,b,w,h]) → FREE positioning, full manual control
# fig.add_subplot(r,c,i) → grid-based, auto-positioned
# plt.subplots(r,c) → grid + returns axes array (most common)

# ══════════════════════════════════════════════════════════════════════════════
# ── 14. Saving a Figure ───────────────────────────────────────────────────────
# plt.savefig() — saves the current figure to a file
# ══════════════════════════════════════════════════════════════════════════════

fig, ax = plt.subplots()
ax.plot([1,2,3], [4,5,6])
ax.set_title("Saved Plot")

plt.savefig("plot.png", # filename (supports .png .jpg .pdf .svg)
dpi=150, # resolution (dots per inch) — higher = sharper
bbox_inches="tight",# crops whitespace around the plot
facecolor="white") # background color
# plt.show() not needed — just saves to file # Output: plot.png saved in working directory

# ══════════════════════════════════════════════════════════════════════════════
# ── 15. Styles / Themes ───────────────────────────────────────────────────────
# plt.style.use() — apply a built-in theme to all plots that follow
# ══════════════════════════════════════════════════════════════════════════════

# print(plt.style.available) # list all available styles
plt.style.use("seaborn-v0_8") # clean seaborn theme
fig, ax = plt.subplots(figsize=(5,5))
ax.plot([1,2,3,4], [1,4,9,16])
ax.set_title("Seaborn Style")
plt.show() # Output: plot with seaborn background and gridlines

plt.style.use("ggplot") # ggplot theme — grey background, colorful lines
plt.style.use("dark_background") # dark mode
plt.style.use("default") # reset to matplotlib default

# ══════════════════════════════════════════════════════════════════════════════
# ── Quick Reference ───────────────────────────────────────────────────────────
# ══════════════════════════════════════════════════════════════════════════════

# plt.plot(x,y) → line plot
# plt.bar(x,y) → vertical bar chart
# plt.barh(x,y) → horizontal bar chart
# plt.scatter(x,y) → scatter plot
# plt.hist(data, bins=n) → histogram
# plt.pie(values) → pie chart
# plt.subplots(r,c) → grid of plots
# plt.title("...") → plot title
# plt.xlabel("...") → x-axis label
# plt.ylabel("...") → y-axis label
# plt.legend() → show legend
# plt.grid(True) → add grid
# plt.show() → display plot
# plt.savefig("f.png", dpi=150) → save to file
# plt.tight_layout() → fix spacing
# plt.style.use("seaborn-v0_8") → apply theme
# fig, ax = plt.subplots() → OOP style — 1 plot
# fig, axes = plt.subplots(r, c) → OOP style — grid, access via axes[row, col]
# fig = plt.figure(figsize=(w,h)) → blank canvas with size control
# ax.set_xlim(a, b) → x-axis range
# ax.set_ylim(a, b) → y-axis range
# ax.set_xticks([...]) → custom tick positions
# ax.set_xticklabels([...]) → custom tick labels
# ax.annotate("txt", xy=, xytext=) → annotate with arrow
# ax.text(x, y, "txt") → plain text label
# fig.add_axes([l, b, w, h]) → custom-positioned axes (inset plots)
# fig.add_subplot(r, c, i) → grid-based axes on a blank figure

No comments:

Post a Comment

Please comment below to feedback or ask questions.