Basic Plot Creation in Matplotlib
Basic Plot Creation in Matplotlib: Complete Guide
Data visualization ka foundation hain yeh 8 chart types. Line chart se lekar Box plot tak — har chart ka basic version, professional styled version, aur har parameter ki detail explanation ke saath.
📑 Is Guide Mein 8 Chart Types Cover Honge:
- Line Chart: plt.plot() — Trends over time dikhana
- Bar Chart: plt.bar() — Category comparison
- Horizontal Bar: plt.barh() — Readable category bars
- Scatter Plot: plt.scatter() — Relationship between 2 variables
- Histogram: plt.hist() — Data distribution
- Pie Chart: plt.pie() — Percentage breakdown
- Box Plot: plt.boxplot() — Spread & outliers
- Area Chart: plt.stackplot() — Cumulative trends
1. plt.plot() — Line Chart
🔍 Kya Hai: Line chart data points ko straight lines se connect karta hai — time ke saath trends dikhane ke liye sabse common chart hai.
💻 Basic Version:
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
revenue = [45000, 52000, 48000, 61000, 55000, 67000]
plt.plot(months, revenue)
plt.title("Monthly Revenue")
plt.xlabel("Month")
plt.ylabel("Revenue (₹)")
plt.show()
💻 Professional Styled Version:
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
revenue_2023 = [45000, 52000, 48000, 61000, 55000, 67000]
revenue_2024 = [50000, 58000, 53000, 69000, 62000, 75000]
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(months, revenue_2023,
color="#3498db", # line color (hex code)
linewidth=2.5, # line thickness
linestyle="-", # solid line ("-", "--", "-.", ":")
marker="o", # data point marker ("o","s","^","D","*")
markersize=8, # marker size
markerfacecolor="white", # marker fill color
markeredgecolor="#3498db", # marker border color
markeredgewidth=2, # marker border thickness
label="2023", # legend label
alpha=0.9, # transparency (0=invisible, 1=solid)
zorder=2 # layer order (higher=front)
)
ax.plot(months, revenue_2024,
color="#e74c3c",
linewidth=2.5,
linestyle="--",
marker="s",
markersize=8,
markerfacecolor="white",
markeredgecolor="#e74c3c",
markeredgewidth=2,
label="2024",
alpha=0.9,
zorder=2
)
# Title & Labels
ax.set_title("Monthly Revenue Comparison", fontsize=16, fontweight="bold", pad=15)
ax.set_xlabel("Month", fontsize=12, labelpad=10)
ax.set_ylabel("Revenue (₹)", fontsize=12, labelpad=10)
# Grid
ax.grid(True, linestyle="--", alpha=0.3, zorder=0)
# Legend
ax.legend(fontsize=11, loc="upper left", framealpha=0.9)
# Spine styling
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.tight_layout()
plt.savefig("line_chart.png", dpi=150, bbox_inches="tight")
plt.show()
📋 All Parameters Explained:
| Parameter | Values | Description |
|---|---|---|
color | "red", "#3498db", "rgb" | Line ka color |
linewidth | 0.5, 1, 2, 3... | Line ki thickness |
linestyle | "-", "--", "-.", ":" | Solid, dashed, dash-dot, dotted |
marker | "o","s","^","D","*","+" | Circle, square, triangle, diamond, star, plus |
markersize | 4, 6, 8, 10... | Marker ka size |
alpha | 0.0 to 1.0 | Transparency level |
label | Any string | Legend mein dikhne wala name |
zorder | 1, 2, 3... | Layer order — higher = front mein |
2. plt.bar() — Vertical Bar Chart
🔍 Kya Hai: Bar chart categories ko rectangular bars se compare karta hai — har bar ki height value represent karti hai. Category comparison ka king hai.
💻 Basic Version:
departments = ["IT", "HR", "Finance", "Marketing", "Operations"]
avg_salary = [82500, 55800, 75200, 62400, 48200]
plt.bar(departments, avg_salary)
plt.title("Average Salary by Department")
plt.ylabel("Salary (₹)")
plt.show()
💻 Professional Styled Version (with Data Labels):
departments = ["IT", "HR", "Finance", "Marketing", "Operations"]
avg_salary = [82500, 55800, 75200, 62400, 48200]
# Color gradient — highest=dark, lowest=light
colors = ["#1a5276", "#7fb3d8", "#2980b9", "#5dade2", "#aed6f1"]
fig, ax = plt.subplots(figsize=(10, 6))
bars = ax.bar(departments, avg_salary,
color=colors, # individual bar colors
width=0.6, # bar width (0 to 1)
edgecolor="#2c3e50", # bar border color
linewidth=1.2, # bar border thickness
alpha=0.9, # transparency
zorder=2 # layer order
)
# Data Labels — har bar ke upar value dikhana
for bar, val in zip(bars, avg_salary):
ax.text(
bar.get_x() + bar.get_width() / 2, # x position (center of bar)
bar.get_height() + 1000, # y position (slightly above bar)
f"₹{val:,}", # formatted text
ha="center", # horizontal alignment
va="bottom", # vertical alignment
fontsize=10, # text size
fontweight="bold", # text weight
color="#2c3e50" # text color
)
ax.set_title("Average Salary by Department", fontsize=16, fontweight="bold", pad=15)
ax.set_xlabel("Department", fontsize=12)
ax.set_ylabel("Average Salary (₹)", fontsize=12)
ax.grid(axis="y", linestyle="--", alpha=0.3, zorder=0)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.tight_layout()
plt.savefig("bar_chart.png", dpi=150, bbox_inches="tight")
plt.show()
📋 All Parameters Explained:
| Parameter | Values | Description |
|---|---|---|
color | single color ya list | Bar fill color — list dene se har bar alag color |
width | 0.1 to 1.0 | Bar ki width — 0.8 default, 0.6 clean dikhta hai |
edgecolor | color string/hex | Bar ka border color |
linewidth | 0.5, 1, 1.5... | Bar border ki thickness |
alpha | 0.0 to 1.0 | Transparency |
bottom | number/array | Stacked bars ke liye base value |
3. plt.barh() — Horizontal Bar Chart
🔍 Kya Hai: Horizontal bar chart category names lambe hone par vertical bars se zyada readable hota hai. Ranking dikhane ke liye best hai — longest bar = highest value clearly dikhai deta hai.
💻 Professional Styled Version:
products = ["Samsung Galaxy S24", "iPhone 15 Pro", "OnePlus 12",
"Google Pixel 8", "Nothing Phone 2"]
sales = [15200, 18500, 12800, 8900, 6500]
# Sort for ranking effect
sorted_data = sorted(zip(sales, products))
sales_sorted = [x[0] for x in sorted_data]
products_sorted = [x[1] for x in sorted_data]
fig, ax = plt.subplots(figsize=(10, 6))
bars = ax.barh(products_sorted, sales_sorted,
color="#2ecc71", # bar color
height=0.5, # bar height (barh mein width ki jagah height)
edgecolor="#27ae60", # border color
linewidth=1, # border thickness
alpha=0.85 # transparency
)
# Data labels — bar ke end mein value
for bar, val in zip(bars, sales_sorted):
ax.text(
bar.get_width() + 200, # x position (right of bar)
bar.get_y() + bar.get_height() / 2, # y position (center)
f"{val:,} units",
ha="left", va="center",
fontsize=10, fontweight="bold"
)
ax.set_title("Top Selling Smartphones", fontsize=16, fontweight="bold", pad=15)
ax.set_xlabel("Units Sold", fontsize=12)
ax.grid(axis="x", linestyle="--", alpha=0.3)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.tight_layout()
plt.savefig("horizontal_bar.png", dpi=150, bbox_inches="tight")
plt.show()
4. plt.scatter() — Scatter Plot
🔍 Kya Hai: Scatter plot do continuous variables ke beech relationship dikhata hai — har dot ek data point hai. Correlation, clusters, outliers — sab ek glance mein visible hote hain.
💻 Professional Styled Version:
import numpy as np
np.random.seed(42)
experience = np.random.uniform(1, 20, 100)
salary = experience * 5000 + np.random.normal(0, 8000, 100) + 30000
performance = np.random.uniform(1, 5, 100)
fig, ax = plt.subplots(figsize=(10, 7))
scatter = ax.scatter(experience, salary,
c=performance, # color mapped to 3rd variable
cmap="RdYlGn", # colormap (Red-Yellow-Green)
s=performance * 40, # size mapped to variable (bubble chart!)
alpha=0.7, # transparency
edgecolors="#2c3e50", # dot border color
linewidth=0.5, # dot border thickness
zorder=2 # layer order
)
# Colorbar — 3rd variable ka legend
cbar = plt.colorbar(scatter, ax=ax, shrink=0.8, label="Performance Rating")
# Trend line
z = np.polyfit(experience, salary, 1)
p = np.poly1d(z)
ax.plot(sorted(experience), p(sorted(experience)),
"--", color="red", linewidth=1.5, alpha=0.7, label="Trend Line")
ax.set_title("Experience vs Salary (Bubble = Performance)", fontsize=15, fontweight="bold")
ax.set_xlabel("Experience (Years)", fontsize=12)
ax.set_ylabel("Salary (₹)", fontsize=12)
ax.legend(fontsize=10)
ax.grid(True, linestyle="--", alpha=0.3)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.tight_layout()
plt.savefig("scatter_plot.png", dpi=150, bbox_inches="tight")
plt.show()
📋 Scatter-Specific Parameters:
| Parameter | Values | Description |
|---|---|---|
c | array/list | 3rd variable ko color se represent karna |
cmap | "viridis","RdYlGn","coolwarm" | Color gradient map |
s | number ya array | Dot size — array dene se bubble chart banta hai |
edgecolors | color string | Dot ka border color |
5. plt.hist() — Histogram (Distribution)
🔍 Kya Hai: Histogram continuous data ki frequency distribution dikhata hai — data ko bins (ranges) mein divide karke har bin mein kitne values hain yeh bars se represent karta hai. Skewness, outliers, distribution shape — sab dikhta hai.
💻 Professional Styled Version:
np.random.seed(42)
salaries = np.random.normal(65000, 15000, 1000)
fig, ax = plt.subplots(figsize=(10, 6))
n, bins_edges, patches = ax.hist(salaries,
bins=25, # number of bins (ranges)
color="#3498db", # bar color
edgecolor="white", # bar border
linewidth=1, # border thickness
alpha=0.8, # transparency
density=False, # True = probability, False = count
histtype="bar", # "bar","step","stepfilled","barstacked"
rwidth=0.9, # bar width relative to bin
zorder=2
)
# Mean & Median reference lines
ax.axvline(np.mean(salaries), color="red", linewidth=2, linestyle="--", label=f"Mean: ₹{np.mean(salaries):,.0f}")
ax.axvline(np.median(salaries), color="green", linewidth=2, linestyle="-.", label=f"Median: ₹{np.median(salaries):,.0f}")
ax.set_title("Salary Distribution", fontsize=16, fontweight="bold")
ax.set_xlabel("Salary (₹)", fontsize=12)
ax.set_ylabel("Number of Employees", fontsize=12)
ax.legend(fontsize=11)
ax.grid(axis="y", linestyle="--", alpha=0.3)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.tight_layout()
plt.savefig("histogram.png", dpi=150, bbox_inches="tight")
plt.show()
📋 Histogram-Specific Parameters:
| Parameter | Values | Description |
|---|---|---|
bins | 10, 20, 50, "auto" | Kitne bins (ranges) mein divide karna hai |
density | True / False | True = probability, False = count |
histtype | "bar","step","stepfilled" | Bar style — step = outline only |
rwidth | 0.5 to 1.0 | Bar width relative to bin — 0.9 clean gap deta hai |
cumulative | True / False | True = cumulative frequency histogram |
6. plt.pie() — Pie Chart
🔍 Kya Hai: Pie chart whole ka parts dikhata hai — percentage breakdown visualize karne ke liye. Circle ko slices mein divide karta hai jahan har slice ek category ki proportion represent karta hai.
💻 Professional Styled Version:
departments = ["IT", "HR", "Finance", "Marketing", "Operations"]
emp_count = [3200, 2400, 2000, 1500, 900]
colors = ["#3498db", "#2ecc71", "#e74c3c", "#f39c12", "#9b59b6"]
explode = (0.05, 0, 0, 0, 0) # IT slice slightly pulled out
fig, ax = plt.subplots(figsize=(8, 8))
wedges, texts, autotexts = ax.pie(emp_count,
labels=departments, # slice labels
colors=colors, # slice colors
autopct="%1.1f%%", # percentage format inside slices
startangle=90, # rotation start angle
explode=explode, # pull out specific slices
shadow=True, # 3D shadow effect
textprops={"fontsize": 11}, # label font size
pctdistance=0.75, # percentage text position (0=center, 1=edge)
labeldistance=1.1, # label position from center
wedgeprops={ # slice styling
"edgecolor": "white",
"linewidth": 2
}
)
# Style percentage text
for autotext in autotexts:
autotext.set_color("white")
autotext.set_fontweight("bold")
ax.set_title("Employee Distribution by Department", fontsize=16, fontweight="bold", pad=20)
plt.tight_layout()
plt.savefig("pie_chart.png", dpi=150, bbox_inches="tight")
plt.show()
📋 Pie-Specific Parameters:
| Parameter | Values | Description |
|---|---|---|
autopct | "%1.1f%%", "%d%%" | Percentage format string |
startangle | 0, 90, 140... | First slice ki starting angle |
explode | tuple (0.05, 0, 0...) | Slice ko center se pull out karna |
shadow | True / False | 3D shadow effect |
pctdistance | 0.5, 0.7, 0.85 | % text ki center se distance |
wedgeprops | dict | Slice styling — edgecolor, linewidth |
🍩 Donut Chart Variation:
# Donut Chart — center mein hole
fig, ax = plt.subplots(figsize=(8, 8))
wedges, texts, autotexts = ax.pie(emp_count,
labels=departments, colors=colors,
autopct="%1.1f%%", startangle=90,
wedgeprops={"width": 0.4, "edgecolor": "white", "linewidth": 2}, # width=0.4 makes donut!
pctdistance=0.8
)
# Center text
ax.text(0, 0, f"Total\n{sum(emp_count):,}", ha="center", va="center", fontsize=16, fontweight="bold")
ax.set_title("Employee Distribution (Donut)", fontsize=15, fontweight="bold")
plt.savefig("donut_chart.png", dpi=150, bbox_inches="tight")
plt.show()
7. plt.boxplot() — Box Plot (Spread & Outliers)
🔍 Kya Hai: Box plot data ki 5-number summary (min, Q1, median, Q3, max) ek box mein dikhata hai. Outliers dots ke roop mein separately dikhte hain. Distribution spread, skewness, aur outliers ek chart mein — EDA ka essential tool.
💻 Professional Styled Version:
np.random.seed(42)
it_salary = np.random.normal(82000, 15000, 200)
hr_salary = np.random.normal(55000, 10000, 200)
fin_salary = np.random.normal(75000, 12000, 200)
mkt_salary = np.random.normal(62000, 18000, 200)
data = [it_salary, hr_salary, fin_salary, mkt_salary]
labels = ["IT", "HR", "Finance", "Marketing"]
fig, ax = plt.subplots(figsize=(10, 6))
bp = ax.boxplot(data,
labels=labels, # x-axis labels
patch_artist=True, # fill boxes with color (IMPORTANT!)
notch=True, # confidence interval notch
showmeans=True, # show mean marker
meanprops={"marker": "D", "markerfacecolor": "red", "markersize": 8},
showfliers=True, # show outlier dots
flierprops={"marker": "o", "markerfacecolor": "#e74c3c", "markersize": 5},
whiskerprops={"linewidth": 1.5},
capprops={"linewidth": 1.5},
medianprops={"color": "#2c3e50", "linewidth": 2}
)
# Color each box
box_colors = ["#3498db", "#2ecc71", "#e74c3c", "#f39c12"]
for patch, color in zip(bp["boxes"], box_colors):
patch.set_facecolor(color)
patch.set_alpha(0.7)
ax.set_title("Salary Distribution by Department", fontsize=16, fontweight="bold")
ax.set_ylabel("Salary (₹)", fontsize=12)
ax.grid(axis="y", linestyle="--", alpha=0.3)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.tight_layout()
plt.savefig("box_plot.png", dpi=150, bbox_inches="tight")
plt.show()
📋 BoxPlot-Specific Parameters:
| Parameter | Values | Description |
|---|---|---|
patch_artist | True / False | True = boxes ko color fill karna (ZAROORI!) |
notch | True / False | Confidence interval notch dikhana |
showmeans | True / False | Mean marker dikhana (diamond) |
showfliers | True / False | Outlier dots dikhana |
whis | 1.5 (default), 2, 3 | Whisker length as IQR multiplier |
vert | True / False | False = horizontal box plot |
8. plt.stackplot() — Stacked Area Chart
🔍 Kya Hai: Stacked area chart multiple categories ki cumulative trend dikhata hai. Har layer ek category represent karti hai aur total height combined value dikhata hai. Revenue breakdown by product category over time — iske liye perfect hai.
💻 Professional Styled Version:
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
electronics = [30000, 35000, 28000, 42000, 38000, 45000]
fashion = [20000, 22000, 25000, 28000, 30000, 35000]
grocery = [15000, 16000, 14000, 18000, 17000, 20000]
fig, ax = plt.subplots(figsize=(10, 6))
ax.stackplot(months, electronics, fashion, grocery,
labels=["Electronics", "Fashion", "Grocery"], # legend labels
colors=["#3498db", "#e74c3c", "#2ecc71"], # layer colors
alpha=0.8, # transparency
edgecolor="white", # layer borders
linewidth=0.5 # border thickness
)
ax.set_title("Revenue by Category (Stacked)", fontsize=16, fontweight="bold")
ax.set_xlabel("Month", fontsize=12)
ax.set_ylabel("Revenue (₹)", fontsize=12)
ax.legend(loc="upper left", fontsize=10)
ax.grid(axis="y", linestyle="--", alpha=0.3)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.tight_layout()
plt.savefig("stacked_area.png", dpi=150, bbox_inches="tight")
plt.show()
💻 Simple Area Chart (Single Series — fill_between):
# Single area chart
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(months, electronics, color="#3498db", linewidth=2)
ax.fill_between(months, electronics,
color="#3498db", # fill color
alpha=0.3 # transparency (0.2-0.4 best for area)
)
ax.set_title("Electronics Revenue Trend", fontsize=15, fontweight="bold")
plt.savefig("area_chart.png", dpi=150, bbox_inches="tight")
plt.show()
Quick Reference: Kaunsa Chart Kab Use Karein?
| Purpose | Chart Type | Function |
|---|---|---|
| Trend over time | Line Chart | plt.plot() |
| Category comparison | Bar Chart | plt.bar() / plt.barh() |
| Relationship (2 variables) | Scatter Plot | plt.scatter() |
| Data distribution | Histogram | plt.hist() |
| Percentage breakdown | Pie / Donut | plt.pie() |
| Spread & outliers | Box Plot | plt.boxplot() |
| Cumulative category trends | Stacked Area | plt.stackplot() |
Next Post: Part 2
Next part mein hum cover karenge: Styling, Annotations & Layout — titles, labels, data labels, annotations, subplots, themes aur chart ko professional level tak polish karne ke complete tools.
Happy Visualizing! 📊🚀
💬 Comments (0)
Loading comments...