Python Notes
Master Matplotlib, Python
Matplotlib is Python's foundational plotting library. It provides a MATLAB-like interface for creating a wide variety of static, animated, and interactive visualizations. Most other plotting libraries (Seaborn, Pandas plots) are built on top of Matplotlib.
Installation
pip install matplotlibimport matplotlib.pyplot as plt
import numpy as np
print(plt.matplotlib.__version__)Basic Plot Anatomy
Line Charts
Bar Charts
Scatter Plots
Histograms and Distributions
Box Plots
Pie and Donut Charts
Subplots and Layouts
Heatmaps
Saving and Styling
Summary
In this lesson, you learned:
- ✅ Matplotlib architecture (Figure, Axes)
- ✅ Line charts with multiple series and annotations
- ✅ Bar charts (vertical, horizontal, grouped)
- ✅ Scatter plots with color coding and regression lines
- ✅ Histograms and KDE density plots
- ✅ Box plots for distribution comparison
- ✅ Pie and donut charts
- ✅ Creating multi-panel subplot dashboards
- ✅ Heatmaps for 2D data
- ✅ Styling, customization, and saving figures
📤 Code Output Reference
Matplotlib code examples produce visual plots. यहाँ हर example का expected output describe किया गया है:
Line Charts Output
Output: 1. First plot: A line chart showing monthly sales from Jan–Dec with blue line, circle markers, and grid lines. Sales trend goes upward from $12,000 to $35,000. File saved: monthly_sales.png 2. Second plot: Three overlapping lines (Revenue in blue solid, Costs in red dashed, Profit in green dotted) from 2022–2026. Each profit point has a dollar annotation label above it.
Bar Charts Output
Output: 1. Left subplot: Simple vertical bar chart showing Q1 sales for 5 categories (Laptops highest at $45,000). Each bar has a value label on top. 2. Right subplot: Grouped bar chart comparing Q1 (blue) vs Q2 (coral) sales side by side for each category. Q2 shows growth across all categories. 3. Third figure: Horizontal bar chart ranking Q2 sales with colored bars and white value labels inside each bar. Laptops lead with $52,000.
Scatter Plots Output
Output: 1. Left subplot: Scatter plot of 200 points showing house size (x) vs price (y) with a red dashed regression line. Clear positive correlation visible. 2. Right subplot: Same data but color-coded by number of bedrooms (2BR=blue, 3BR=green, 4BR=orange, 5BR=red). Larger homes tend to have more bedrooms and higher prices.
Histograms Output
Output: 1. Left subplot: Histogram of salary data with 40 bins showing trimodal distribution (peaks at ~$30K, ~$65K, ~$110K). Red dashed line = mean, orange dashed = median. 2. Middle subplot: Same histogram with density normalization and a smooth blue KDE curve overlaid. 3. Right subplot: Three overlapping semi-transparent histograms (green=Junior, blue=Mid, red=Senior) clearly showing salary separation by level.
Box Plots Output
Output: 1. Left subplot: Five colored box plots (one per department). Engineering has highest median (~$95K) and widest spread. HR has lowest median (~$65K). Outliers shown as circles. 2. Right subplot: Same box plots but with individual data points scattered (jittered) behind each box, showing the actual distribution density within each department.
Pie and Donut Charts Output
Output: 1. Left subplot: Pie chart with 5 colored slices. Engineering (35%) is slightly exploded outward. Each slice shows percentage label. White edges separate slices. 2. Right subplot: Donut chart (pie with white circle in center). Center displays "Total 100%". Same data and colors as pie chart but with hollow center.
Subplots Dashboard Output
Output: A 2×3 grid of bar charts, each showing monthly sales (Jan–Jun) for a different product (Laptop, Mouse, Keyboard, Monitor, Headphones, Webcam). Each subplot uses a unique color. Main title "Product Sales Dashboard - 2025" appears at top. File saved: sales_dashboard.png
Heatmap Output
Output: A color-coded heatmap (Yellow-Orange-Red colormap) showing sales activity across 7 days × 12 time slots. Weekday business hours (Mon–Fri, 08:00–16:00) show highest intensity (darker red). Each cell contains its numeric value. Colorbar on right shows scale (10–280+).
Saving and Styling Output
Output: 1. Print statement shows first 10 available styles: ['Solarize_Light2', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-v0_8', ...] 2. Plot shows sin(x) as blue solid line and cos(x) as red dashed line from 0 to 10. Clean style with no top/right spines. Three files saved: trig.png, trig.pdf, trig.svg.
⚠️ Common Mistakes
| # | ❌ Mistake | ✅ Fix |
|---|---|---|
| 1 | plt.show() के बाद plot modify करने की कोशिश करना — show() figure को clear कर देता है | plt.show() हमेशा last में call करो। Modifications पहले करो। |
| 2 | plt.plot() call करना but plt.show() भूल जाना — Jupyter के बाहर कोई window नहीं दिखती | हर plotting block के end में plt.show() या plt.savefig() ज़रूर लगाओ। |
| 3 | Multiple plots एक ही figure में mix हो जाना — पिछला plot अगले के साथ overlap करता है | हर new plot से पहले plt.figure() या plt.clf() use करो। |
| 4 | figsize को बहुत small रखना जिससे labels overlap हो जाते हैं या cut हो जाते हैं | plt.tight_layout() use करो और figsize को appropriate set करो (minimum (8, 5))। |
| 5 | plt.savefig() को plt.show() के बाद call करना — empty/blank file save होती है | savefig() पहले call करो, show() बाद में। show() figure buffer clear करता है। |
| 6 | Bar chart में x positions manually set न करना जब grouped bars बनाते हो — bars overlap हो जाते हैं | np.arange() से positions calculate करो और width offset use करो: x - width/2, x + width/2। |
| 7 | Large datasets पर plt.plot() use करना plt.scatter() की जगह — performance slow और lines messy | 1000+ unordered points के लिए scatter() use करो। Connected sequential data के लिए plot()। |
✅ Key Takeaways
- 📊 Matplotlib Python की foundational plotting library है — Seaborn, Pandas plots सब इसी पर built हैं
- 🏗️ Figure → Axes hierarchy समझो: Figure is the canvas, Axes is the actual plot area
- 📈 Line charts time-series/trends के लिए best हैं,
markeradd करो individual points दिखाने के लिए - 📊 Bar charts categorical comparison के लिए ideal हैं — grouped bars के लिए
np.arange()+ width offset use करो - 🔵 Scatter plots relationship/correlation दिखाने के लिए हैं —
cparameter से color-coding औरsसे size-coding कर सकते हो - 📉 Histograms distribution दिखाते हैं —
binscount adjust करो data granularity के according - 🎨 Customization matters:
plt.style.use()से quick theming,rcParamsसे global defaults set करो - 💾 Always save before show:
fig.savefig('name.png', dpi=300, bbox_inches='tight')— high quality export - 📐
tight_layout()हमेशा use करो — ये labels को overlap/crop होने से बचाता है - 🧹 Memory management:
plt.close('all')use करो loops में plots generate करते वक्त, otherwise memory leak होगा
❓ FAQ
Q1: Matplotlib और Seaborn में क्या difference है? कब कौन use करें?
Answer: Matplotlib low-level library है — full control मिलता है but ज़्यादा code लिखना पड़ता है। Seaborn high-level है, built on Matplotlib — statistical plots जल्दी बनते हैं with better defaults। Quick statistical visualizations के लिए Seaborn use करो, custom/complex layouts के लिए Matplotlib best है। दोनों एक साथ भी use कर सकते हो! 🎨
Q2: plt.plot() vs plt.subplots() — कौन सा approach better है?
Answer: plt.plot() quick single plots के लिए ठीक है (state-based/pyplot interface)। But professional work के लिए fig, ax = plt.subplots() (object-oriented interface) better है क्योंकि — multiple axes handle कर सकते हो, code readable है, और complex layouts आसानी से बनते हैं। Always prefer OO approach! ✅
Q3: Plot save करने पर blank/white image आती है — कैसे fix करें?
Answer: ये इसलिए होता है क्योंकि plt.savefig() को plt.show() के बाद call किया। show() figure buffer clear कर देता है। Fix: savefig() हमेशा show() से पहले call करो। या figure object use करो: fig.savefig('plot.png') — ये reliable है। 💾
Q4: Matplotlib plot में Hindi/Unicode text कैसे add करें?
Answer: Matplotlib Unicode support करता है by default। बस font specify करो जो Hindi glyphs support करे: plt.rcParams['font.family'] = 'Noto Sans Devanagari' या 'Mangal'। फिर directly Hindi text use कर सकते हो: plt.title('बिक्री रिपोर्ट 2025')। Font install होना ज़रूरी है system पर। 🔤
Q5: Interactive plots कैसे बनाएं — zoom, hover features चाहिए?
Answer: Matplotlib में %matplotlib notebook (Jupyter) से basic interactivity मिलती है। Advanced interactivity के लिए mplcursors library use करो (hover tooltips) या Plotly/Bokeh consider करो। plt.ion() से interactive mode ON कर सकते हो scripts में। 🖱️
Q6: Plot का resolution/quality कैसे improve करें for publication?
Answer: dpi parameter increase करो: plt.savefig('plot.png', dpi=300) (print quality)। Vector formats (PDF, SVG) use करो — ये infinitely scalable हैं: fig.savefig('plot.pdf')। bbox_inches='tight' से extra whitespace remove होता है। Journals typically 300+ DPI PNG या vector format demand करते हैं। 📄
Q7: Multiple plots को एक figure में arrange कैसे करें (complex layouts)?
Answer: Simple grid: plt.subplots(rows, cols) use करो। Complex/unequal layouts: GridSpec use करो — from matplotlib.gridspec import GridSpec। gs = GridSpec(3, 3, figure=fig) से custom spans define कर सकते हो like ax1 = fig.add_subplot(gs[0, :]) (full top row)। 📐
Q8: Dark mode/custom theme कैसे apply करें?
Answer: Built-in dark style: plt.style.use('dark_background')। Custom theme: plt.rcParams.update({...}) से global settings change करो। Multiple styles combine भी कर सकते हो: plt.style.use(['seaborn-v0_8', 'dark_background'])। Company branding colors एक dict में define करके reuse करो। 🌙
🎯 Interview Questions
Q1: Matplotlib में Figure और Axes में क्या difference है? Object-Oriented vs Pyplot interface explain करो।
Answer:
- Figure = entire window/canvas जिसमें plots रहते हैं। Think of it as a blank paper।
- Axes = actual plot area within figure (title, x-axis, y-axis, data सब यहाँ)। एक Figure में multiple Axes हो सकते हैं।
- Pyplot interface (
plt.plot()) — state-based, quick & simple, implicitly current figure/axes manage करता है। Quick exploration के लिए अच्छा। - OO interface (
fig, ax = plt.subplots()) — explicit, full control, better for complex figures, production code, और reusable functions।
Q2: plt.savefig() blank image save करता है — possible causes और fix बताओ।
Answer:
- Cause 1:
plt.show()पहले call हुआ — ये figure buffer clear करता है - Cause 2: Wrong figure reference — multiple figures open हैं
- Fix: Always call
savefig()BEFOREshow(), या figure object directly use करो:fig.savefig('output.png', dpi=300, bbox_inches='tight') bbox_inches='tight'ensures labels don't get cut off
Q3: Large dataset (1M+ points) plot करना है — performance कैसे optimize करें?
Answer:
- Downsampling: Plot से पहले data reduce करो (every nth point, or aggregation)
rasterized=True: Vector plots में heavy elements को rasterize करो:ax.scatter(x, y, rasterized=True)plt.plot()overplt.scatter(): Line plots are faster than scatter for ordered data- Agg backend: Non-interactive backend use करो:
matplotlib.use('Agg')— no GUI overhead - Datashader/Holoviews: 10M+ points के लिए specialized libraries consider करो
Q4: Subplots में axes share कैसे करते हैं? इसका advantage क्या है?
Answer:
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True, figsize=(10, 8))sharex=True: All subplots same x-axis range share करते हैं — comparison easysharey=True: Same y-axis range — fair visual comparison- Advantage: Consistent scale across plots, less clutter (shared labels), better data comparison
- Individual axis sharing:
ax2 = ax1.twinx()— dual y-axis (e.g., temperature + rainfall)
Q5: Matplotlib में color maps (cmaps) क्या हैं? कब कौन सा cmap use करना चाहिए?
Answer:
- Sequential (
viridis,plasma,Blues): Single variable low→high — heatmaps, density - Diverging (
RdBu,coolwarm,seismic): Center point से deviation — correlation matrices, temperature anomaly - Qualitative (
Set1,tab10,Paired): Categorical/distinct groups — pie charts, group colors - Perceptually uniform (
viridis,magma): Equal visual difference = equal data difference — prefer these for accuracy cmap='viridis'is default and colorblind-friendly ✅
Q6: Real-time/live data plot कैसे करें Matplotlib में?
Answer:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
fig, ax = plt.subplots()
xdata, ydata = [], []
line, = ax.plot([], [], 'b-')
ax.set_xlim(0, 100)
ax.set_ylim(-1, 1)
def update(frame):
xdata.append(frame)
ydata.append(np.sin(frame * 0.1))
line.set_data(xdata, ydata)
return line,
ani = animation.FuncAnimation(fig, update, frames=100, interval=50, blit=True)
plt.show()FuncAnimationframe-by-frame update करता हैblit=Trueperformance improve करता है (only changed parts redraw)intervalmilliseconds में delay set करता है between frames
Q7: Matplotlib plot को web application (Flask/Django) में कैसे serve करें?
Answer:
- Key points:
Aggbackend (no GUI),BytesIOfor in-memory save,plt.close()for memory, base64 encode for HTML embedding
Q8: Explain tight_layout() vs constrained_layout — कब कौन use करें?
Answer:
tight_layout(): Post-hoc adjustment — plot बनने के बाद spacing fix करता है। Simple cases में well काम करता है।plt.tight_layout()याfig.tight_layout()constrained_layout: Set at creation time:plt.subplots(constrained_layout=True). More robust, handles colorbars, suptitles, nested axes better।- Rule: Complex layouts (colorbars, suptitle, GridSpec) →
constrained_layout=True। Simple subplots →tight_layout()sufficient।
Q9: Matplotlib figure को Pandas DataFrame से directly कैसे plot करें?
Answer:
- Pandas
.plot()internally Matplotlib use करता है —axobject return होता है जिसे further customize कर सकते हो kindparameter:'line','bar','barh','scatter','hist','box','pie'
Q10: Production code में Matplotlib best practices क्या हैं?
Answer:
- Always use OO interface —
fig, ax = plt.subplots()(not pyplot state machine) - Close figures —
plt.close(fig)loops में, otherwise memory leak - Set backend early —
matplotlib.use('Agg')for scripts/servers (before importing pyplot) - Use style sheets — consistent look:
plt.style.use('company_style') bbox_inches='tight'— always insavefig()to avoid cut-off labels- DPI for context — screen: 100, presentation: 150, print: 300+
- Colorblind-friendly — use
viridis/cividiscmaps, avoid red-green only - Reproducible —
np.random.seed()set करो if random data generate कर रहे हो - Vector for papers — PDF/SVG save करो publications के लिए, PNG for web
- Type hints + docstrings — plotting functions को properly document करो
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Data Visualization with Matplotlib.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, data, science, matplotlib
Related Python Master Course Topics