Matplotlib — প্রথম গ্রাফ
এই পাঠে যা শিখবেন
- Matplotlib কী — দু'টি interface (pyplot vs OO)
- Line, scatter, bar, histogram — চার মৌলিক plot
- Subplots — একাধিক chart একসাথে
- Title, label, legend, grid — cosmetics
- plt.savefig — file-এ export
- AI workflow-এ — loss curve, distribution চেক
১ · Matplotlib কী?
Matplotlib (২০০৩, John Hunter) — Python-এর সবচেয়ে পুরনো ও বহুল ব্যবহৃত plotting library। NumPy/Pandas-এর সাথে seamlessly কাজ করে। AI/ML-এর প্রতিটি notebook-এ এর উপস্থিতি — training loss দেখা থেকে শুরু করে feature distribution বোঝা পর্যন্ত। Seaborn, Plotly, Pandas plotting — সবাই internally Matplotlib-এর উপর দাঁড়ানো (অথবা inspiration নেয়)।
২ · দু'টি interface — pyplot বনাম OO
১) pyplot — MATLAB-style state-machine। plt.plot(), plt.title() — global "current figure"-এ কাজ। দ্রুত prototyping।
২) Object-Oriented — fig, ax = plt.subplots()। প্রতিটি call explicit ax.plot(), ax.set_title()। Production-এ recommended।
import matplotlib.pyplot as plt
import numpy as np
# Style 1 — pyplot (MATLAB-style)
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
plt.title("pyplot style")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.show()
# Style 2 — Object-Oriented (production)
fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(x, np.sin(x), color="purple")
ax.set_title("OO style")
ax.set_xlabel("x")
ax.set_ylabel("sin(x)")
plt.show()
ax object explicit — একাধিক subplot, library code, reproducibility — সব জায়গায় পরিষ্কার।
৩ · Line plot — training loss-এর ভাষা
Line plot সবচেয়ে common — একটি continuous variable-এর পরিবর্তন দেখায়। AI training-এ loss curve এর সর্বোত্তম উদাহরণ — epoch বনাম loss।
import matplotlib.pyplot as plt
import numpy as np
# একটি বাস্তবসম্মত training loss curve simulate
np.random.seed(42)
epochs = np.arange(1, 31)
train_loss = 2.5 * np.exp(-0.15 * epochs) + 0.05 * np.random.rand(30)
val_loss = 2.5 * np.exp(-0.12 * epochs) + 0.10 * np.random.rand(30) + 0.05
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(epochs, train_loss, color="#2563eb", marker="o",
linestyle="-", label="Training loss")
ax.plot(epochs, val_loss, color="#dc2626", marker="s",
linestyle="--", label="Validation loss")
ax.set_title("Training vs Validation Loss")
ax.set_xlabel("Epoch")
ax.set_ylabel("Loss")
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()
color, marker, linestyle, label — line plot-এর চার প্রধান cosmetic parameter। legend() automatic label-গুলো দেখায়।
৪ · Scatter plot — দু'টি feature, এক চোখে
Scatter plot দু'টি continuous variable-এর সম্পর্ক দেখায়। Marker size ও color দিয়ে আরও দু'টি dimension যোগ করা যায় — মোট ৪-D info এক plot-এ।
import matplotlib.pyplot as plt
import numpy as np
# Iris-জাতীয় ২ class data
np.random.seed(0)
class_0 = np.random.randn(50, 2) + [2, 2]
class_1 = np.random.randn(50, 2) + [5, 5]
fig, ax = plt.subplots(figsize=(6, 5))
ax.scatter(class_0[:, 0], class_0[:, 1],
c="#2563eb", s=50, alpha=0.7, label="Class 0")
ax.scatter(class_1[:, 0], class_1[:, 1],
c="#dc2626", s=50, alpha=0.7, label="Class 1")
ax.set_title("Two-feature scatter — class দ্বারা color")
ax.set_xlabel("Feature 1 (পাপড়ির দৈর্ঘ্য)")
ax.set_ylabel("Feature 2 (পাপড়ির প্রস্থ)")
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()
s = marker size, c = color, alpha = transparency (overlap বুঝতে)। দু'টি class পরিষ্কার আলাদা — মানে এই দু'টি feature classifier-এর জন্য informative।
৫ · Bar chart — categorical comparison
Bar chart — একটি categorical variable-এর প্রতিটি class-এ একটি সংখ্যা। যেমন: প্রতিটি model-এর accuracy, প্রতিটি class-এ কতটি sample।
import matplotlib.pyplot as plt
models = ["LR", "SVM", "RF", "XGBoost", "MLP"]
accuracy = [0.78, 0.84, 0.88, 0.91, 0.87]
fig, ax = plt.subplots(figsize=(7, 4))
bars = ax.bar(models, accuracy,
color=["#94a3b8", "#60a5fa", "#34d399", "#fbbf24", "#f472b6"])
# প্রতিটি বার-এর উপর সংখ্যা দেখানো
for bar, acc in zip(bars, accuracy):
ax.text(bar.get_x() + bar.get_width()/2, acc + 0.005,
f"{acc:.2f}", ha="center", fontsize=10)
ax.set_title("Model comparison — test accuracy")
ax.set_ylabel("Accuracy")
ax.set_ylim(0.7, 1.0)
plt.show()
plt.barh() দিয়ে horizontal bar পাওয়া যায় — long category name-এর জন্য সুবিধাজনক। উপরের সংখ্যাগুলো (annotation) reader-কে দ্রুত বোঝাতে সাহায্য করে।
৬ · Histogram — distribution বোঝা
Histogram — একটি continuous variable-এর মান কোথায় বেশি কেন্দ্রিভূত। Outlier detection, normality check, feature engineering — সব কিছুর জন্য জরুরি।
import matplotlib.pyplot as plt
import numpy as np
# একটি skewed distribution — যেমন আয়
np.random.seed(7)
income = np.random.lognormal(mean=10.5, sigma=0.6, size=2000)
fig, ax = plt.subplots(figsize=(7, 4))
ax.hist(income, bins=40, color="#7c3aed",
edgecolor="white", alpha=0.85)
ax.set_title("আয়ের distribution (BDT)")
ax.set_xlabel("আয় (BDT)")
ax.set_ylabel("ব্যক্তি সংখ্যা")
ax.axvline(np.median(income), color="red",
linestyle="--", label=f"median = {np.median(income):,.0f}")
ax.legend()
plt.show()
bins selection critical — কম bins-এ pattern miss, বেশি bins-এ noise। Sturges' rule বা Freedman-Diaconis দিয়ে শুরু, তারপর ম্যানুয়ালি tune। Skewed data-তে log-transform helpful।
৭ · Subplots — একাধিক plot একসাথে
subplotsSubplotsএকই Figure-এ একাধিক Axes — grid layout-এ। plt.subplots(rows, cols) Figure ও Axes array ফেরায়। AI-তে প্রতিটি feature বা প্রতিটি class আলাদা panel-এ দেখাতে অপরিহার্য। দিয়ে এক Figure-এ একাধিক chart — comparison সহজ। plt.subplots(rows, cols) একটি Figure ও Axes-এর array ফেরায়।
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1)
x = np.linspace(0, 10, 100)
fig, axes = plt.subplots(2, 2, figsize=(10, 7))
# Top-left — line
axes[0, 0].plot(x, np.sin(x), color="#2563eb")
axes[0, 0].set_title("sin(x)")
# Top-right — scatter
axes[0, 1].scatter(np.random.randn(80), np.random.randn(80),
c="#dc2626", alpha=0.6)
axes[0, 1].set_title("Random scatter")
# Bottom-left — histogram
axes[1, 0].hist(np.random.randn(1000), bins=30,
color="#16a34a", edgecolor="white")
axes[1, 0].set_title("Normal distribution")
# Bottom-right — bar
axes[1, 1].bar(["A", "B", "C", "D"], [3, 7, 2, 5], color="#f59e0b")
axes[1, 1].set_title("Bar")
fig.suptitle("2×2 Subplots — চার ধরনের plot একসাথে", fontsize=14)
fig.tight_layout()
plt.show()
axes একটি 2-D NumPy array — axes[row, col] দিয়ে index। fig.tight_layout() overlap এড়াতে — auto spacing।
৮ · Cosmetics — title, label, legend, grid
একটি plot informative হতে গেলে context চাই — title, axis label, legend, grid, axis limits — সব মিলিয়ে।
ax.set_title("...")— chart titleax.set_xlabel(),ax.set_ylabel()— অক্ষের নাম + এককax.legend()— labels-এর keyax.grid(True, alpha=0.3)— light gridax.set_xlim(a, b),ax.set_ylim(a, b)— axis rangeax.set_xticks([...]),ax.set_yticks([...])— tick controls
plt.close(fig) বা plt.close("all") call করুন। Matplotlib figure GC করে না — server-এ memory দ্রুত শেষ।
৯ · Save — figure file-এ export
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(x, np.cos(x), color="#0891b2")
ax.set_title("Saved plot")
# Different formats — PNG, PDF, SVG
fig.savefig("plot.png", dpi=150, bbox_inches="tight")
fig.savefig("plot.pdf", bbox_inches="tight")
fig.savefig("plot.svg", bbox_inches="tight")
plt.close(fig) # memory free
print("Saved: plot.png, plot.pdf, plot.svg")
dpi=100, paper-এ dpi=300। SVG/PDF — vector, যেকোনো scale-এ sharp।
১০ · AI workflow — Matplotlib কোথায় কোথায়?
- Training loss curve: overfit/underfit একনজরে।
- Confusion matrix preview:
imshowদিয়ে heatmap। - Feature distribution: histogram — outlier ও skewness।
- Learning rate schedule: warm-up + decay visualize।
- Gradient norm: per-layer magnitude — vanishing/exploding ধরা।
- Sample prediction: image + predicted label grid।
- Hyperparameter sweep: grid search-এর heatmap।
কোনো ডেটাসেট পেলে — আগে plot করুন। Distribution দেখুন (hist), feature relations দেখুন (scatter), missing pattern দেখুন (bar)। Model ছাড়াই ৮০% insight chart থেকেই আসে। Andrew Ng-র "data-centric AI" এই philosophy-র উপর দাঁড়ানো।
ভাবনার প্রশ্ন
প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।
প্র ০১
pyplot বনাম OO interface — কোনটা কখন? Notebook prototyping ও production code-এ আপনার সিদ্ধান্ত কী হবে এবং কেন?
এই প্রশ্ন Matplotlib শেখার প্রথম দিনে অনেক confusion তৈরি করে। কারণ official documentation, Stack Overflow, এমনকি একই notebook-এও দু'টি style mixed দেখা যায়। কিন্তু কখন কোনটা — এর একটি স্পষ্ট mental model থাকা জরুরি।
pyplot (state-machine) — গভীর পরিচিতি:
- MATLAB-এর syntax-এ অনুপ্রাণিত।
plt.plot(),plt.title(),plt.xlabel()— সব global "current figure"-এ apply। - Behind the scenes —
plt.gca()(get current axes) call করে। - Multiple figure থাকলে তখন
plt.figure(1),plt.figure(2)দিয়ে switch। - সরল, দ্রুত — ৫ লাইনের EDA-তে অসাধারণ।
OO (object-oriented) — গভীর পরিচিতি:
- প্রতিটি Figure ও Axes একটি explicit Python object।
fig, ax = plt.subplots()— পরিষ্কার ownership।- একই function-এ দু'টি subplot manipulate — কোন কনফিউশন নেই।
- Library code-এ প্রায় বাধ্যতামূলক।
Notebook prototyping-এ pyplot ভাল কেন?
- Cell-by-cell exploration — current figure context সহজে maintain।
- কম typing, দ্রুত iteration।
- Single chart-এ বেশি কাজ করতে গেলে boilerplate কম।
Production-এ OO কেন বাধ্যতামূলক?
- Reusability: function বানালে —
def plot_loss(ax, losses): ax.plot(...)। Caller তার নিজের axes পাঠায়। - Subplot management: dashboard-এ ৬টি chart — pyplot-এ নিয়ন্ত্রণ অসম্ভব।
- Testing: figure return করলে — pixel comparison test সহজ।
- Concurrency: background thread/process-এ pyplot-এর global state race condition তৈরি করে।
- Memory: explicit
plt.close(fig)— leak এড়ানো।
Hybrid pattern (অনেক popular library-তে):
def plot_history(history, ax=None):
if ax is None:
fig, ax = plt.subplots()
ax.plot(history["loss"], label="train")
ax.plot(history["val_loss"], label="val")
ax.legend()
return ax
Caller চাইলে নিজের axes পাঠাবে, নইলে function নতুন বানাবে। Seaborn এই pattern follow করে।
মূল উপলব্ধি: Notebook-এ scratch pad — pyplot ঠিক। কিন্তু যখনই function বানান বা একাধিক subplot — OO-তে switch করুন। অভ্যাস হলে OO দ্রুতই হয় এবং অনেক বেশি predictable।
প্র ০২ AI training-এ কোন কোন graph essential? Loss curve, learning rate schedule, validation gap, gradient norm — প্রতিটির insight ও কখন কোনটা দেখবেন বিশ্লেষণ করুন।
AI training একটি অনেকটা "অন্ধকারে শট" — মডেলের ভিতরে কী হচ্ছে directly দেখা যায় না। তাই plots-ই আমাদের diagnostic tool। ভাল engineer এই plots একনজরে পড়তে পারেন এবং সঠিক intervention নিতে পারেন।
(১) Training & Validation Loss Curve — সবচেয়ে মৌলিক:
- X-axis: epoch / step। Y-axis: loss।
- Both decreasing: learning হচ্ছে ✓।
- Train ↓, val ↑: overfitting — regularization, dropout, early stop চাই।
- Both flat high: underfitting — model capacity বা lr বাড়ান।
- Train fluctuating wildly: lr বেশি — কমান।
- Sudden spike: bad batch বা NaN — gradient clipping।
- Y-axis log scale-এ দেখলে ছোট improvement-ও spotted।
(২) Learning Rate Schedule:
- X-axis: step। Y-axis: lr।
- Warm-up (linear up) → constant/cosine decay — modern LLM-এ standard।
- Visualize করলে — schedule code-এ bug ধরা পড়ে (constant হয়ে গেছে কিনা)।
- Loss curve-এর সাথে overlay — কোথায় lr drop হলো, কোথায় loss নামল।
(৩) Validation Gap (train-val difference):
- Train_loss − val_loss vs epoch — generalization-এর direct signal।
- Gap বাড়ছে = memorizing শুরু।
- Early stopping criterion — gap threshold cross করলে।
(৪) Gradient Norm — per layer:
- প্রতিটি layer-এর gradient magnitude plot।
- Vanishing gradient: deep layers-এ near-zero — old RNN-এর সমস্যা।
- Exploding gradient: sudden spike — gradient clipping জরুরি।
- BatchNorm/LayerNorm-এর effectiveness measure।
(৫) Weight Histogram per Layer (Distribution):
- Initialization ঠিক আছে? Training-এ shift কতটা?
- Dead neuron (সব 0) detect।
- TensorBoard-এ standard view।
(৬) Activation Distribution:
- প্রতিটি layer-এর output distribution।
- ReLU saturation (অনেক 0) — dying ReLU problem।
- Tanh/sigmoid saturation — vanishing gradient predictor।
(৭) Confusion Matrix (classification):
- Heatmap — কোন class অন্য class-এ confused।
- Class imbalance, label noise, hard examples — সব এতে।
(৮) Per-class Accuracy / F1 bar chart:
- Average accuracy ভাল হলেও — কিছু class হয়ত poor।
- Production decision-এর জন্য critical।
(৯) Sample Predictions Grid:
- Image classification — wrong predictions visualize।
- Pattern খুঁজে পান — "blurry hole image-এ fail"।
(১০) Loss Landscape (advanced):
- 2-D projection — sharp vs flat minima।
- Generalization theory-র research level।
মূল উপলব্ধি: "Trust no metric you haven't plotted" — visualization debugging-এর প্রথম step। Loss curve trivial মনে হলেও — ৮০% training disaster এই plot দেখেই বোঝা যায়। TensorBoard, Weights & Biases (W&B), MLflow — সব এই অভ্যাসকে scale করে।
প্র ০৩ Visualization-এ common ভুল কী কী? Wrong scale, missing axis label, misleading aspect ratio, color choice (colorblind-unfriendly) — দায়িত্বশীল ভিজ্যুয়াল কেমন?
ভাল chart যেমন insight দেয়, তেমনি bad chart misinformation ছড়ায়। Edward Tufte-র শতাব্দী-প্রাচীন কাজ, সাম্প্রতিক "Calling Bullshit" boi — সব দেখাচ্ছে data visualization-এর ethics কতটা গুরুত্বপূর্ণ।
(১) Truncated Y-axis — সবচেয়ে common deception:
- Bar chart — y-axis 0 থেকে শুরু না হলে ছোট পার্থক্য বিশাল দেখায়।
- "Model A 91%, Model B 92%" — y-axis 90-93 হলে B "twice as good" দেখায়।
- Bar chart-এ y-axis সবসময় 0 থেকে শুরু — non-negotiable rule।
- Line plot-এ truncation acceptable (trend বুঝতে), কিন্তু label করুন।
(২) Wrong scale (linear vs log):
- Income, population, training loss — লেখক নন-linear; log scale-এ দেখা উচিত।
- COVID case curve linear scale-এ exponential চাপা পড়ে।
- Loss curve initial drop linear-এ দেখা যায়, পরের subtle gain log-এ।
- Ruling: data কয়েক order of magnitude জুড়ে — log try করুন।
(৩) Missing axis labels & units:
- "Time" নয়, "Time (seconds)"। "Loss" নয়, "Cross-entropy loss"।
- Reader-কে অনুমান করতে দেবেন না।
- Title — what; xlabel/ylabel — units; legend — series।
(৪) Misleading aspect ratio:
- Tall narrow chart — small change exaggerated।
- Wide flat chart — change suppressed।
- Cleveland's rule — slope গড়ে ৪৫° হলে human perception best।
- Scientific publication-এ standard ratio (যেমন 1.6:1) মেনে চলুন।
(৫) Color choice — colorblind-unfriendly:
- ৮% পুরুষ red-green colorblind। Red/green-এ পার্থক্য করতে পারে না।
- Use
viridis,cividis,plasma— perceptually uniform। - Diverging data-তে
RdBu_rবাBrBG। - Color + shape/pattern combine — redundancy।
- Wong palette — colorblind-safe।
(৬) 3-D bar chart:
- প্রায় সবসময় খারাপ — perspective ভুল reading তৈরি করে।
- 2-D সমপরিমাণ বেশি accurate পড়া যায়।
(৭) Pie chart abuse:
- ৩-৫ category-র বেশি — bar chart সব সময় ভাল।
- Angle-এ percentage বুঝা মানুষের কঠিন।
- Tufte: "the only worse than a pie chart is several pie charts"।
(৮) Overplotting:
- 10K points scatter-এ — সব overlap, pattern অদৃশ্য।
- Solution:
alpha=0.3, hexbin, 2-D histogram, density plot।
(৯) Cherry-picked time range:
- "Last 5 days-এ stock 20% up" — কিন্তু 1-year-এ 50% down।
- Context সবসময় দিন।
(১০) Dual y-axis trap:
- দু'টি ভিন্ন unit — same plot-এ overlay। Misleading correlation দেখাতে পারে।
- Better — দু'টি subplot পাশাপাশি।
দায়িত্বশীল ভিজ্যুয়াল checklist:
- ✓ Title clearly states what is shown
- ✓ Both axes labeled with units
- ✓ Legend present যদি multiple series
- ✓ Y-axis 0 থেকে শুরু (bar chart-এ)
- ✓ Colorblind-safe palette
- ✓ Source/date noted
- ✓ Aspect ratio reasonable
- ✓ "What's the message?" — এক sentence-এ বলতে পারলে chart সফল
মূল উপলব্ধি: Visualization = communication। Reader-এর mind-এ accurate model বানানোই লক্ষ্য। বিভ্রান্তিকর chart — যাই হোক unintentional — credibility ধ্বংস করে। AI engineer-এর responsibility শুধু code নয়, সঠিক communication-ও।
প্র ০৪ Matplotlib বনাম Plotly বনাম D3 — কখন কোনটা? Static vs interactive, Python-only vs web — trade-off ও সিদ্ধান্ত framework।
২০২৫-এ visualization landscape অনেক rich। ভুল tool বাছলে — ৫ গুণ বেশি কাজ। সঠিক বাছাই depends use-case, audience, deployment, ও skill set-এর উপর।
Matplotlib — strengths:
- Most mature (২০০৩+), gigantic ecosystem।
- Publication-quality static (PDF, SVG, PNG)।
- Full pixel-level control।
- Pandas, NumPy, scikit-learn — সবার সাথে seamless।
- Offline, no JavaScript dependency।
Matplotlib — weaknesses:
- API verbose, default style কিছুটা dated।
- Interactivity weak — zoom/pan basic।
- Web embedding awkward।
- 3-D rendering sluggish।
Plotly — strengths:
- Interactive by default — hover, zoom, select।
- Web-friendly — HTML output, Dash framework।
- Modern look out of the box।
- 3-D, geo, financial charts strong।
- Python, R, JavaScript — same API।
Plotly — weaknesses:
- Bundle size large (3 MB JS)।
- Static export-এ Kaleido dependency।
- Customization Matplotlib-র চেয়ে কঠিন কখনও।
- Print-quality publication-এ second choice।
D3.js — strengths:
- সর্বোচ্চ flexibility — যেকোনো visualization বানানো সম্ভব।
- NYT, FT, Bloomberg-র award-winning interactive।
- SVG-based, infinite scaling।
- Web-native।
D3.js — weaknesses:
- Steep learning curve — JavaScript + SVG + data-binding।
- একটি custom chart-ই সপ্তাহ লাগে।
- Python ecosystem থেকে দূরে।
- Maintenance burden।
আরও কিছু consider করার:
- Seaborn: Matplotlib-এর উপর — statistical plots-এ চমৎকার। সুন্দর default।
- Altair: declarative grammar-of-graphics। Vega-Lite-এর Python wrapper। মাঝারি data-এ অসাধারণ।
- Bokeh: Plotly-র alternative। দ্রুত, server integration ভাল।
- Holoviews/HvPlot: Pandas-এর সাথে one-liner interactive।
- Observable Plot: D3-র modern, easier successor।
সিদ্ধান্ত framework:
- Notebook EDA, paper figure: Matplotlib + Seaborn।
- Internal dashboard: Plotly + Dash, বা Streamlit + Plotly।
- Public web product: Plotly বা Observable Plot। Custom-এ D3।
- Award-winning data journalism: D3 — যদি বাজেট থাকে।
- Quick statistical exploration: Seaborn।
- Streaming/realtime dashboard: Bokeh।
- Geographic data: Folium (leaflet wrapper) বা Plotly।
AI engineer-এর pragmatic stack (২০২৫):
- ৭০% — Matplotlib + Seaborn (notebook, paper, report)।
- ২০% — Plotly (interactive sharing, dashboard)।
- ১০% — Streamlit/Gradio + Plotly (demo apps)।
- D3 — অধিকাংশ AI work-এ overkill।
Performance consideration:
- 10K points — সবগুলো ভাল।
- 1M points — Datashader, Vaex, deck.gl।
- Realtime — WebGL-based (Plotly's
scattergl, deck.gl)।
মূল উপলব্ধি: Tool বাছাই = audience × deployment × time budget। Matplotlib AI engineer-এর "default text editor" — শিখতেই হবে। Plotly secondary — interactive-এ। D3 নিজেই একটি career path — সচরাচর AI work-এ লাগে না। সঠিক tool = সঠিক story।
অনুশীলন
-
Line plot: NumPy দিয়ে $y = x^2$ ও $y = x^3$ ($x$: -5 to 5) — একই plot-এ দু'টি curve, দু'টি color, legend ও grid সহ আঁকুন।
import matplotlib.pyplot as plt import numpy as np x = np.linspace(-5, 5, 200) fig, ax = plt.subplots(figsize=(7, 4)) ax.plot(x, x**2, color="#2563eb", label="$y = x^2$") ax.plot(x, x**3, color="#dc2626", label="$y = x^3$") ax.set_title("Polynomial curves") ax.set_xlabel("x") ax.set_ylabel("y") ax.legend() ax.grid(True, alpha=0.3) ax.axhline(0, color="black", linewidth=0.5) ax.axvline(0, color="black", linewidth=0.5) plt.show() -
Histogram with bin tuning: ১০,০০০ samples — normal distribution। তিনটি subplot — bins=5, bins=30, bins=200। কোনটা সবচেয়ে informative?
import matplotlib.pyplot as plt import numpy as np np.random.seed(0) data = np.random.randn(10000) fig, axes = plt.subplots(1, 3, figsize=(13, 4)) for ax, b in zip(axes, [5, 30, 200]): ax.hist(data, bins=b, color="#7c3aed", edgecolor="white", alpha=0.85) ax.set_title(f"bins = {b}") ax.set_xlabel("value") fig.suptitle("Bin selection-এর প্রভাব", fontsize=14) fig.tight_layout() plt.show() # bins=5 — পুরো shape miss # bins=30 — ভাল balance, normal curve পরিষ্কার # bins=200 — noisy, individual fluctuation বেশি -
2×2 subplots dashboard: চারটি random series — line, scatter, hist, bar — চারটি panel-এ সাজান। প্রতিটিতে title, axis label, ও suptitle যোগ করুন।
import matplotlib.pyplot as plt import numpy as np np.random.seed(2) fig, axes = plt.subplots(2, 2, figsize=(10, 7)) # Line t = np.linspace(0, 4*np.pi, 200) axes[0, 0].plot(t, np.sin(t) * np.exp(-0.1*t), color="#2563eb") axes[0, 0].set_title("Damped oscillation") axes[0, 0].set_xlabel("time"); axes[0, 0].set_ylabel("amplitude") # Scatter x = np.random.randn(150); y = 0.5*x + np.random.randn(150)*0.5 axes[0, 1].scatter(x, y, c="#dc2626", alpha=0.6) axes[0, 1].set_title("Correlated random") axes[0, 1].set_xlabel("x"); axes[0, 1].set_ylabel("y") # Histogram axes[1, 0].hist(np.random.exponential(2, 1000), bins=40, color="#16a34a", edgecolor="white") axes[1, 0].set_title("Exponential distribution") axes[1, 0].set_xlabel("value"); axes[1, 0].set_ylabel("count") # Bar axes[1, 1].bar(["Q1", "Q2", "Q3", "Q4"], [120, 145, 138, 162], color="#f59e0b") axes[1, 1].set_title("Quarterly sales") axes[1, 1].set_ylabel("BDT (lakh)") fig.suptitle("Mini Dashboard", fontsize=15, y=1.02) fig.tight_layout() plt.show()
আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ
- পাঠ ১৮ · Seaborn — সুন্দর ডেটা ভিজ্যুয়াল পরবর্তী পাঠ Matplotlib-এর উপর built — statistical plots one-liner-এ।
- পাঠ ১৬ · Missing data handling আগের পাঠ NaN-detection, fillna, dropna — Pandas data cleaning।
- পাঠ ১৪ · Pandas পরিচিতি এই পাঠের সাথে সম্পর্কিত DataFrame.plot() — Matplotlib-এর Pandas wrapper।
- সব AI Courses দেখুন ABCL TECH Python, ML, DL, NLP, CV, GenAI, RL, MLOps — সব AI কোর্স একসাথে।