1.4.8 · HinglishPython & Scientific Computing

Matplotlib and Seaborn visualization

2,978 words14 min readRead in English

1.4.8 · AI-ML › Python & Scientific Computing

Overview

Data visualization numerical arrays ko visual insights mein transform karta hai. Matplotlib Python ki foundational plotting library hai (MATLAB-jaisi API), jabki Seaborn ek statistical visualization layer hai jo Matplotlib ke upar bani hai, better defaults aur statistical functions ke saath.


Core Concepts


Matplotlib Fundamentals

The Object-Oriented Pattern (WHY/HOW)

OO interface kyun use karein?

  • Explicit control: Tum jaante ho ki tum kis Axes pe draw kar rahe ho (subplots ke liye critical)
  • Reproducibility: Koi hidden global state nahi
  • Composability: Functions ax ko argument ke roop mein accept kar sakte hain

Anatomy kaise kaam karta hai:

import matplotlib.pyplot as plt
import numpy as np
 
# Create container and plot area
fig, ax = plt.subplots(figsize=(8, 6))  # figure size in inches
 
# Generate data
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
 
# Plot on the Axes object
ax.plot(x, y, label='sin(x)', color='blue', linewidth=2)
 
# Customize the Axes
ax.set_xlabel('Radians', fontsize=12)
ax.set_ylabel('Amplitude', fontsize=12)
ax.set_title('Sine Wave Demonstration', fontsize=14, fontweight='bold')
ax.legend(loc='upper right')
ax.grid(True, alpha=0.3)
 
plt.tight_layout()  # Prevent label clipping
plt.show()

Yeh step kyun?

  • fig, ax = plt.subplots(): Ek Figure aur ek single Axes unpack karta hai. 2×2 grid ke liye: fig, axes = plt.subplots(2, 2) se axes[0,0], axes[0,1], wagera milte hain.
  • ax.plot(): Is specific Axes pe draw karta hai, kisi global state pe nahi
  • tight_layout(): Spacing auto-adjust karta hai taaki labels overlap na karein

Seaborn: Statistical Visualization

Distribution Plots

Relationship Plots

Categorical Plots


Common Mistakes & Fixes


Advanced Techniques


Memory Aid


Active Recall Questions

Recall Matplotlib ko ek 12-saal ke bacche ko explain karo

Socho tumhare paas ek blank poster board hai (woh hai Figure). Tum uspe ek grid paper tape karte ho (woh hai Axes). Ab tum time ke saath apne test scores ka ek line graph draw karte ho—woh line ek Artist hai (kuch visible).

Tum ek poster pe multiple grid papers tape kar sakte ho (subplots). Har grid ka apna graph hai.

Matplotlib = draw karne ke tools. Seaborn = ek smart assistant jo tumhare liye common patterns draw karta hai (jaise "mere liye ek graph draw karo jo dikhaye ki kya lambe log zyada weight karte hain, aur automatically ek best-fit line add karo").


Connections


#flashcards/ai-ml

Matplotlib mein do main interfaces kaunse hain aur inhe kab use karna chahiye? :: pyplot (state-machine) jaise plt.plot() quick REPL sketches ke liye. Object-oriented jaise fig, ax = plt.subplots(); ax.plot() production code ke liye kyunki tumhare paas explicit control hai ki tum kaunsa Axes modify kar rahe ho, reproducibility aur composability enable hoti hai.

Matplotlib mein Figure aur Axes mein kya fark hai?
Figure poora canvas/window hai. Axes (note: plural, "axis" nahi) figure ke andar ek single plot area hai apne coordinate system ke saath. Ek Figure mein multiple Axes (subplots) ho sakte hain.
Training loss plot karte waqt ax.set_yscale('log') kyun use karein?
Training ke dauran loss aksar exponentially decrease hota hai. Log scale curve ki tail (baad ke epochs mein chhote improvements) ko visible banata hai, warna woh zero ke paas compress ho jaati.
ax.hist() mein density=True kya karta hai aur ise kyun use karein?
Histogram ko normalize karta hai taaki total area 1 ho jaaye, isse probability density mein convert karta hai. Yeh tumhe comparison ke liye theoretical PDF curves overlay karne deta hai.
Seaborn ke regplot() mein regression line ke aas-paas shaded region kya represent karta hai?
Regression line ke liye 95% confidence interval. Yeh dikhata hai: "Agar hum data ko kai baar resample karein, toh 95% fitted lines is band se guzrengi." Wide bands high uncertainty indicate karti hain.
Violin plot boxplot se behtar kyun hai?
Violin plots poori distribution shape dikhate hain (kya yeh bimodal hai? skewed? uniform?) jabki boxplots sirf quartiles dikhate hain, potentially important distribution characteristics jaise multiple peaks chhupa dete hain.
Bar chart kabhi zero se shuru nahi karna chahiye?
Interval scales (accuracy, temperature) ke liye jahan zero meaningful baseline nahi hai. Example: 89%, 90%, 91% accuracy waale models compare karna—0 se shuru karne pe differences invisible ho jaate hain. Ratio scales (revenue, count) 0 se shuru hone chahiye.
'jet' colormap se kyun bachein?
(1) Perceptually uniform nahi—yellow same intensity pe bhi red se "brighter" lagta hai. (2) Colorblind-safe nahi—8% men red/green mein distinguish nahi kar sakte. (3) Grayscale mein print karne pe structure kho jaata hai. Iske bajaye 'viridis' ya 'plasma' use karo.
Code safety ke terms mein plt.plot() aur ax.plot() mein kya fark hai?
plt.plot() global implicit state ("current" Axes) modify karta hai, functions aur loops mein bugs create karta hai. ax.plot() explicitly specify karta hai ki kis Axes pe draw karna hai, code ko reproducible aur composable banata hai.
Text place karte waqt transform=ax.transAxes kya karta hai?
Text ko data coordinates ki jagah Axes coordinates (plot area ke andar 0-1 normalized) mein place karta hai. Example: ax.text(0.5, 0.9, 'Title', transform=ax.transAxes) text ko data range chahe kuch bhi ho, top-center pe rakhta hai.
Publications ke liye figures save karte waqt kaunsa DPI use karna chahiye?
Print publications ke liye 300 DPI (dots per inch) standard hai. Saath mein bbox_inches='tight' bhi use karo excess whitespace hatane ke liye: plt.savefig('plot.png', dpi=300, bbox_inches='tight').
Confusion matrices ke liye sns.heatmap() kyun use karein?
Turant reveal karta hai kaunse classes confuse ho rahe hain (off-diagonal cells). Color intensity error magnitude dikhati hai. annot=True exact counts overlay karta hai, visual aur numerical information combine karta hai.
Seaborn mein histogram mein kde=True kya add karta hai?
Kernel Density Estimate overlay karta hai—ek smooth curve jo underlying probability distribution dikhati hai, har data point pe ek Gaussian kernel place karke aur unhe sum karke estimate ki jaati hai.
Plot ko colorblind-accessible kaise banayein?
Perceptually-uniform colormaps use karo: 'viridis', 'plasma', 'cividis' (sab colorblind-safe hain). Categorical data ke liye 'Set2' ya 'tab10' use karo. Red-green combinations se bachein. Colorblind simulator se test karo.
plt.tight_layout() ka kya purpose hai?
Subplot spacing aur margins automatically adjust karta hai taaki labels, titles, aur tick marks overlap na hon ya figure edges pe clip na hon.

Concept Map

implemented by

foundational library

built on top of

hierarchical model

contains

holds

interface 1

interface 2

explicit control of

adds

enables

returns

Data Visualization

Matplotlib

Seaborn

Figure fig

Axes ax

Artist

pyplot state-machine

Object-Oriented interface

Statistical defaults

DataFrame integration