Lesson 29 � Data Visualization

MATPLOTLIB:
DATA KO Dikhao.

Data sirf numbers nahi hai � usko charts aur graphs mein dikhana zaroori hai taaki patterns, trends aur comparisons samajh aayein. Matplotlib Python ki sabse purani aur popular visualization library hai.

? 22 min ✓ Intermediate ✓ Prerequisite: Pandas

WHY: Data visualization kyun zaroori hai?

Jab aapke paas 1000 rows ka data ho, usko table mein dekh kar samajhna mushkil hai. Lekin ek chart banao � aur turant pata chal jaata hai kaunsa month best hai, kaun sabse zyada karta hai, ya distribution kaisi hai.

Matplotlib ko import matplotlib.pyplot as plt se load karte hain. plt ek short name hai jo industry mein standard hai.

python
import matplotlib.pyplot as plt
import numpy as np
Mental model: pyplot ek state-machine ki tarah kaam karta hai � jab tak plt.show() nahi bologe, chart display nahi hoga. Har function ek layer add karta hai.

HOW: basic line chart se shuru karo

Line chart sabse simple aur common chart hai. Yeh ek data point ko dusre se connect karta hai � trend dikhane ke liye best.

python
import matplotlib.pyplot as plt

# Basic line chart
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 35]
plt.plot(x, y, marker="o")
plt.title("Sales Trend")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()

Yahan marker="o" har point par dot dikhata hai. title, xlabel, ylabel chart ko label karte hain � bina yeh chart incomplete hota hai.

PLOT

Basic line chart � trend aur time-series data ke liye perfect. plt.plot() se points connect hote hain.

BAR

Bar chart comparison ke liye hai � kaun zyada, kaun kam. plt.bar() se categories ko compare karte hain.

HISTOGRAM

Data ka distribution dikhata hai � kitne values kis range mein hain. plt.hist() se bins mein data split hota hai.

Bar chart: comparison dikhao

Bar chart mein har category ka ek vertical bar hota hai. Color bhi customize kar sakte ho � taaki chart attractive aur readable ho.

python
import matplotlib.pyplot as plt

# Bar chart
students = ["Aman", "Priya", "Rahul"]
marks = [85, 92, 78]
plt.bar(students, marks, color=["gold", "skyblue", "coral"])
plt.title("Marks Comparison")
plt.show()

color parameter mein list de sakte ho � har bar ka alag color hoga. Yeh multiple data series mein bohot useful hai.

Histogram: data distribution samjho

Histogram data ko bins mein divide karta hai. Agar aapko pata karna hai ki scores ka distribution kaisa hai � kitne students 60-70 mein, kitne 70-80 mein � toh histogram best hai.

python
import matplotlib.pyplot as plt
import numpy as np

# Histogram
scores = np.random.normal(75, 10, 1000)
plt.hist(scores, bins=20, edgecolor="black")
plt.title("Score Distribution")
plt.show()
Key insight: np.random.normal(75, 10, 1000) 1000 scores generate karta hai jo mean 75 aur standard deviation 10 ke around hain. Histogram mein bell curve dikhta hai � normal distribution ka sign.

Subplots: ek figure mein multiple charts

Kabhi kabhi ek hi figure mein 2-3 charts dikhane hote hain. plt.subplots() se grid bana sakte ho aur har cell mein alag chart rakh sakte ho.

python
import matplotlib.pyplot as plt

# Subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.plot([1, 2, 3], [1, 4, 9])
ax1.set_title("Line Chart")
ax2.bar(["A", "B", "C"], [3, 7, 5])
ax2.set_title("Bar Chart")
plt.tight_layout()
plt.show()

figsize=(10, 4) chart ka width aur height set karta hai. tight_layout() automatically spacing adjust karta hai taaki labels overlap na karein.

Try it: apna chart banao

Neeche ke editor mein code run karo aur chart ko customize karo � colors badlo, labels change karo, naye data points add karo.

Try it: line chart banao Code edit karke chart dekho
Run Python dabayein

Chart customization tips

Matplotlib mein bahut kuch customize kar sakte ho. Yeh kuch common patterns hain:

python
import matplotlib.pyplot as plt

# Colors aur styles
plt.plot([1, 2, 3], [1, 4, 9], color="red", linestyle="--", linewidth=2)
plt.plot([1, 2, 3], [2, 5, 8], color="green", marker="s")

# Legend
plt.legend(["Squares", "Linear"], loc="upper left")

# Save chart
plt.savefig("chart.png", dpi=150, bbox_inches="tight")
plt.show()

linestyle="--" se dashed line banti hai. marker="s" square markers dikhata hai. savefig() se chart ko PNG file mein save kar sakte ho.

Matplotlib + Pandas: real data visualization

Pandas DataFrame se directly charts bana sakte ho. Yeh real-world data analysis mein sabse zyada use hota hai.

python
import matplotlib.pyplot as plt
import pandas as pd

data = {
 "Month": ["Jan", "Feb", "Mar", "Apr", "May"],
 "Sales": [100, 150, 200, 180, 250]
}
df = pd.DataFrame(data)

# Pandas se directly plot
df.plot(x="Month", y="Sales", kind="bar", title="Monthly Sales")
plt.ylabel("Revenue")
plt.tight_layout()
plt.show()
Pro tip: df.plot() internally Matplotlib use karta hai. Isse aapko alag se x aur y values extract nahi karni padti � DataFrame directly pass karo.

Quick check

Ek line chart banao jo 5 months ka sales data show kare � month 1 se 5 tak aur sales 10, 20, 30, 40, 50.

Pehle matplotlib.pyplot import karo, phir plt.plot() use karo with x aur y lists.

Common mistakes

Matplotlib complete?

Ab aap charts bana sakte ho � line, bar, histogram aur subplots. Next: Python DSA � data structures aur algorithms seekho.