L
LLLOS.ai
Learn
L

Chapter 5 — Data Visualisation Using Pyplot

Class 12 · Computer Science

Overview

Chapter 5 — Data Visualisation Using Pyplot Master Diagram

Introduction: Data-visualisation using Pyplot introduces students to graphical representation of data using the matplotlib.pyplot module in Python. The chapter covers basic plotting functions, customization of plots, and how visual representations help in exploring and communicating patterns, trends, distributions and relationships in data. Importance: Visualisation is a core skill in data analysis — it makes large or complex datasets understandable, reveals hidden patterns, supports decision making, and is widely used in science, business and research. For Class 12 students, learning Pyplot builds practical programming skills, prepares them for data-centric topics in higher studies, and complements theoretical concepts of statistics and computer science. Key themes: The chapter focuses on (1) the pyplot interface and the object-oriented approach to plotting, (2) different chart types (line, bar, histogram, scatter, pie, boxplot etc.), (3) plot customization (labels, titles, legends, colors, markers, line styles, limits and ticks), (4) arranging multiple plots (subplots), (5) reading and plotting data from lists, NumPy arrays and simple CSV/Pandas structures, and (6) saving and…

Learning Objectives

  • Define Pyplot and describe its role in creating 2D visualizations with Matplotlib.
  • Explain the purpose of the import statement 'import matplotlib.pyplot as plt' and common pyplot conventions.
  • Demonstrate how to plot basic chart types (line, bar, scatter, histogram, pie) using pyplot functions.
  • Write Python code to create plots from lists, NumPy arrays, and pandas Series/DataFrame columns.
  • Customize plots by setting axis labels, titles, legends, colors, markers, line styles, and grid lines.
  • Construct single-figure layouts with multiple subplots using plt.subplot and plt.subplots.
  • Adjust figure size, resolution (DPI), and save plots to files using plt.savefig with appropriate formats.
  • Interpret plotted graphs to identify trends, patterns, distributions, and relationships in data.

Topics in this chapter

20 topics · tap a topic title to jump straight to it.

📊1

Introduction to Data Visualization

💻 COMPUTER SCIENCE / IT

Introduction to Data Visualization

Key Point: Mean (average): mean = (x1 + x2 + ... + xn) / n

What is Data Visualization? Data visualization is the graphical representation of data and information using visual elements like charts, graphs and maps. It helps convert raw numbers into visual stories that are easier to understand, compare and interpret.

Why it matters: Visualization reveals patterns, trends, outliers and relationships that are difficult to spot in tables. It supports faster decision making, clearer communication and better insight from data.

Core components of a good visualization: title, axes with labels and units, legend (if multiple series), data markers/lines/bars, scales (linear or logarithmic), annotations and appropriate color/contrast.

Common chart types and when to use them: line charts (trends over time), bar charts (compare categories), scatter plots (relationship between two continuous variables), histograms (distribution of a single variable), pie charts (proportions of a whole — use sparingly), box plots (distribution and outliers), heatmaps (matrix or correlation views).

Principles / best practices: 1) Choose the chart type that matches your question; 2) Keep it simple—avoid chart junk; 3) Label axes and units; 4) Use consistent scales and colors; 5) Highlight important values or trends; 6) Avoid misleading scales (start axis at zero where appropriate).

Steps to create an informative plot (typical workflow): 1) Define the question you want to answer; 2) Clean and summarize the data (aggregate, remove errors); 3) Choose the appropriate visualization; 4) Select scales and colors; 5) Add labels/legend/title; 6) Interpret and communicate findings.

Interpreting visualizations: Look for slope (in line charts), relative heights (in bars), clustering and correlation (in scatter plots), skew and spread (in histograms/box plots). Always check sample size and axis ranges before drawing conclusions.

Common pitfalls to avoid: using pie charts for many categories, truncating axes to exaggerate differences, cluttered legends, too many colors, plotting aggregated data without showing variability.

📌 Examples
  • Trend of daily COVID-19 cases over months — use a line chart to show rise and fall, annotate peaks and lockdown periods.
  • Comparing student enrollment across states — use a vertical bar chart (states on x-axis, student count on y-axis).
  • Distribution of exam scores for a class — use a histogram or box plot to show spread, median and outliers.
  • Relationship between hours studied and marks obtained — use a scatter plot to check correlation and fit a regression line.
  • Market share of smartphone brands in a region — use a bar chart or a carefully labeled pie chart for a few categories.
  • Hourly temperature readings from a sensor — use a line chart with a moving average to smooth short-term noise.
🧮 Formulas
  1. \[Mean (average): mean = (x1 + x2 + ... + xn) / n\]
  2. \[Median: the middle value when data are sorted (or average of two middle values if n is even)\]
  3. \[Mode: the most frequently occurring value in the data set\]
  4. \[Variance: var = (1/n) * Σ(xi - mean)^2\]
  5. \[Standard deviation: sd = sqrt(variance)\]
  6. \[Percent change: ((new - old) / old) × 100%\]
💻2

Matplotlib and Pyplot Overview

💻 COMPUTER SCIENCE / IT

Matplotlib and Pyplot Overview

Key Point: Equation of a straight line used in line plots and trendlines: y = m*x + c (m = slope, c = intercept).

What is Matplotlib?
Matplotlib is a widely used Python library for creating static, interactive, and animated visualizations. It provides a flexible object-oriented API to build plots similar to MATLAB.

What is Pyplot?
Pyplot (imported as import matplotlib.pyplot as plt) is a module in Matplotlib that offers a state-based interface (convenience functions) to create and customize plots quickly. It is ideal for simple scripts and interactive work.

Core concepts / structure

  • Figure: the entire window or image; can contain one or more axes (plots).
  • Axes: an individual plot — contains x-axis, y-axis, data, labels, title.
  • Axis: the x and y (or z) scale and ticks.
  • Artist: any visual element (lines, text, ticks, patches).

Typical workflow (simple)

  • Prepare data (lists, NumPy arrays, Pandas series).
  • Create figure/axes: fig, ax = plt.subplots() or use state interface plt.plot(...).
  • Plot data: ax.plot(x, y), ax.bar(...), ax.scatter(...), etc.
  • Label and style: ax.set_title(), ax.set_xlabel(), ax.set_ylabel(), ax.legend().
  • Show or save: plt.show(), plt.savefig('file.png').

Common Pyplot functions

  • plt.plot() — line plot
  • plt.scatter() — scatter plot
  • plt.bar() / plt.barh() — bar charts
  • plt.hist() — histogram (distribution)
  • plt.pie() — pie chart
  • plt.subplots(nrows, ncols) — multiple plots in one figure
  • Styling: color=, linestyle=, marker=, linewidth=, alpha= (transparency)

Example code snippets

import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [10,20,15,25]
plt.plot(x, y, marker='o', color='b', linestyle='-')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('Simple Line Plot')
plt.grid(True)
plt.show()

Customization and best practices

  • Use figsize=(w,h) to set figure size.
  • Prefer fig, ax = plt.subplots() for clearer code in larger programs.
  • Save plots with sufficient DPI: plt.savefig('plot.png', dpi=300).
  • Label axes and add legends for clarity. Use grids for readability in line/scatter plots.
  • When plotting large datasets, consider downsampling or using specialized libraries (seaborn, plotly) for interactivity.

When to use which plot

  • Line plot: trends over time (temperature, stock prices).
  • Bar chart: comparisons between categories (marks per subject).
  • Histogram: distribution of continuous data (exam scores).
  • Scatter: relationship between two numeric variables (height vs weight).
  • Pie chart: simple percentage share (market share) — use sparingly.

Summary
Matplotlib (with Pyplot) is a fundamental tool for data visualization in Python. Learn the Figure–Axes model, common plotting functions, and how to style and save plots. These skills help present data clearly and support data-driven decisions.

📌 Examples
  • Monthly temperature trend (line plot): Plot daily or monthly average temperature to observe seasonal trends. Code: plt.plot(months, temps, marker='o').
  • Student marks comparison (bar chart): Use a bar chart to compare marks across subjects for one student or across students for one subject. Code: plt.bar(subjects, marks, color='green').
  • Exam score distribution (histogram): Plot scores of a class to see the distribution, mean and spread. Code: plt.hist(scores, bins=10, edgecolor='black').
  • Height vs weight relationship (scatter + trendline): Show correlation between height and weight and add a best-fit line using linear regression (NumPy).
  • Market-share composition (pie chart): Display percentage share of sales among product categories with plt.pie(shares, labels=categories, autopct='%1.1f%%').
🧮 Formulas
  1. \[Equation of a straight line used in line plots and trendlines: y = m*x + c (m = slope\]
    \[c = intercept).\]
  2. \[Slope (m) for simple linear regression (least squares): m = Σ((xi - x̄)(yi - ȳ)) / Σ((xi - x̄)²)\]
    \[where x̄ and ȳ are means.\]
  3. \[Intercept (c) in regression: c = ȳ - m * x̄.\]
  4. \[Mean (average) used to summarize data: x̄ = (1/n) Σ xi.\]
  5. \[Standard deviation (population) to quantify spread: σ = sqrt((1/n) Σ (xi - x̄)²).\]
💻3

Figure and Axes Objects

💻 COMPUTER SCIENCE / IT

Figure and Axes Objects

Key Point: Figure size: figsize = (width_in_inches, height_in_inches). Image pixels = (width_in_inches * dpi, height_in_inches * dpi).

Overview
In Matplotlib (pyplot) a plot is built from objects. The two most important are the Figure and the Axes. The Figure is the whole drawing area or canvas (the window or image). An Axes is a single plot (the region that contains the data, the x/y axes, ticks, labels, title and the plotted lines/markers).

Key roles

  • Figure: top-level container. It can contain multiple Axes (subplots), legends, and figure-level text. Created by plt.figure() or returned with fig from plt.subplots().
  • Axes: the area where data is plotted. Methods like ax.plot(), ax.bar(), ax.set_title(), ax.set_xlabel() are called on an Axes object.
  • Axis: part of an Axes (xaxis, yaxis) controlling tick locations, tick labels and scaling.

Creating Figures and Axes

# common patterns
fig = plt.figure(figsize=(8,5), dpi=100)
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])   # left, bottom, width, height (fractions of figure)

# preferred, simple way:
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8,5))
# for multiple subplots:
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10,8))

Differences between figure-level and axes-level commands

  • Figure-level methods act on the whole figure: fig.suptitle(), fig.savefig(), plt.tight_layout().
  • Axes-level methods act on a specific subplot: ax.plot(), ax.set_xlim(), ax.grid(), ax.legend().

Multiple Axes and Layouts
You can place multiple axes in a figure as a grid (subplots), use inset axes (small axes inside a larger axes), or create shared axes (sharex/sharey) for aligned comparisons. Use fig.add_axes([left, bottom, width, height]) for custom placement (fractions 0–1) and ax.twinx() to share the x-axis but use a second y-axis.

Practical tips

  • Use figsize=(width_inches, height_inches) and dpi to control image resolution. Pixels = inches * dpi.
  • Call fig.tight_layout() (or plt.tight_layout()) to prevent overlapping labels when you have many subplots.
  • Save the figure using fig.savefig('name.png', dpi=150) to export a high-quality image.

Why this matters (CBSE context)
Understanding Figure and Axes is essential for arranging multiple plots, controlling appearance programmatically, and preparing figures for reports or presentations. It separates concerns: the Figure holds the entire output while each Axes handles a particular plotted dataset.

📌 Examples
  • Temperature vs Days (line plot): Use fig, ax = plt.subplots(); ax.plot(days, temps); ax.set_xlabel('Day'); ax.set_ylabel('Temperature (°C)'); fig.savefig('temp_plot.png').
  • Student marks across subjects (bar chart): fig, ax = plt.subplots(); ax.bar(subjects, marks); ax.set_title('Class 12 marks'); use multiple Axes in a 1x2 grid to compare two students.
  • Stock price with volume (time series + twin y-axis): ax.plot(date, price); ax2 = ax.twinx(); ax2.bar(date, volume, alpha=0.3); keeps price and volume scales separate but aligned on x-axis.
  • Inset zoom for sensor data spikes: main ax shows full time series; inset_ax = fig.add_axes([0.6, 0.6, 0.25, 0.25]) with a zoomed-in window of a spike.
  • Multiple distributions (subplots): fig, axes = plt.subplots(2,2); plot histograms of different datasets on each Axes to compare distributions side-by-side.
🧮 Formulas
  1. \[Figure size: figsize = (width_in_inches\]
    \[height_in_inches)\]
    \[Image pixels = (width_in_inches * dpi\]
    \[height_in_inches * dpi).\]
  2. \[Axes position (normalized figure coordinates): [left\]
    \[bottom\]
    \[width\]
    \[height] where values are between 0 and 1 relative to the figure.\]
  3. \[Number of subplots in a grid: total_plots = nrows * ncols.\]
  4. \[Subplot index (plt.subplot): index runs from 1 to nrows*ncols in row-major order (left-to-right\]
    \[top-to-bottom).\]
  5. \[Aspect ratio = width / height (use ax.set_aspect(aspect) to control).\]
💻4

Basic Plotting Functions

📐 MATHEMATICAL FORMULA / THEOREM

Basic Plotting Functions

Key Point: Percentage (for pie/autopct): percentage = (value / total_sum) * 100

Overview
Pyplot (matplotlib.pyplot) provides simple functions to create common 2D plots. Basic plotting functions let you visualize relationships, distributions and comparisons using line plots, scatter plots, bar charts, histograms, pie charts, boxplots and simple area/stack plots. You combine these with axis labels, titles, legends and grid to make informative graphics.

Common plotting functions and usage

  • Line plot — plt.plot(x, y, color='blue', linestyle='-', marker='o', linewidth=2, label='Label')
    Used for trends over an ordered axis (time, sequence).
  • Scatter plot — plt.scatter(x, y, s=30, c='red', alpha=0.6, marker='x')
    Used to show relationship/correlation between two numeric variables.
  • Bar chart — plt.bar(x_positions, heights, width=0.6, color='skyblue', label='Categories')
    Used for categorical comparisons (counts, sums).
  • Horizontal bar — plt.barh(y_positions, widths)
  • Histogram — plt.hist(data, bins=10, color='green', edgecolor='black')
    Used to show distribution and frequency of numeric data.
  • Pie chart — plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
    Shows part-to-whole proportions (use with care for many categories).
  • Boxplot — plt.boxplot(data, vert=True, notch=False)
    Summarizes distribution (median, quartiles, outliers).
  • Stacked/area plot — plt.stackplot(x, y1, y2, colors=['a','b']) or plt.fill_between(x, y1, y2)
    Good for cumulative contributions over time.
  • Stem / step — plt.stem(x, y) and plt.step(x, y) for discrete signals or piecewise constant plots.

Customization & figure control

  • Labels and title: plt.xlabel('X-axis'), plt.ylabel('Y-axis'), plt.title('Title')
  • Legend: plt.legend() — provide label='...' in plot calls
  • Axes limits and ticks: plt.xlim(a, b), plt.ylim(c, d), plt.xticks([...], rotation=45)
  • Grid: plt.grid(True)
  • Multiple plots: plt.subplot() or fig, axes = plt.subplots(rows, cols, figsize=(w,h))
  • Save figure: plt.savefig('filename.png', dpi=300, bbox_inches='tight')

Simple code examples

# Line plot example
x = [1,2,3,4,5]
y = [30, 32, 31, 29, 35]
plt.plot(x, y, color='red', marker='o', linestyle='--', label='Temp')
plt.xlabel('Day')
plt.ylabel('Temperature (°C)')
plt.title('Daily Temperature')
plt.legend()
plt.grid(True)
plt.show()
# Histogram example
scores = [55, 70, 68, 90, 45, 77, 89, 62, 73, 56]
plt.hist(scores, bins=5, color='lightblue', edgecolor='black')
plt.xlabel('Marks')
plt.ylabel('Frequency')
plt.title('Distribution of Student Marks')
plt.show()

Tips for good visualisation

  • Choose appropriate plot type for the question: trends → line, relation → scatter, distribution → histogram/boxplot, composition → pie/stacked area.
  • Keep plots simple: clear labels, readable ticks, appropriate color/marker choices and a legend for multiple series.
  • Normalize or scale data when mixing different units (e.g., use secondary y-axis only when necessary).
📌 Examples
  • Line plot: Plotting daily temperature over a week to show trend and fluctuations.
  • Scatter plot: Showing relationship between hours studied and exam marks to check correlation.
  • Bar chart: Comparing monthly sales of different product categories for a store.
  • Histogram: Visualizing distribution of students' marks to see clustering and skewness.
  • Pie chart: Showing market share percentage of companies in a sector (use few categories).
  • Boxplot: Comparing salary distributions across different departments to spot medians and outliers.
🧮 Formulas
  1. \[Percentage (for pie/autopct): percentage = (value / total_sum) * 100\]
  2. \[Mean (sample): μ = (1/n) * Σ xi\]
  3. \[Variance (sample): σ² = (1/n) * Σ (xi - μ)²\]
  4. \[Standard deviation: σ = sqrt(σ²)\]
  5. \[Pearson correlation coefficient (r) between x and y: r = [Σ(xi - x̄)(yi - ȳ)] / [sqrt(Σ(xi - x̄)²) * sqrt(Σ(yi - ȳ)²)]\]
  6. \[Interquartile range (IQR) for boxplot: IQR = Q3 - Q1\]
    \[whisker bounds commonly = Q1 - 1.5*IQR and Q3 + 1.5*IQR\]
💻5

Line Plots

💻 COMPUTER SCIENCE / IT

Line Plots

Key Point: Equation of a straight line: y = m*x + c (m = slope, c = intercept).

What is a line plot? A line plot (or line chart) is a type of chart that displays information as a series of data points called markers connected by straight line segments. In data visualisation, line plots are ideal for showing trends, changes over continuous intervals (e.g., time), and comparisons between one or more variables.

Line plots in Pyplot (matplotlib.pyplot)
Matplotlib's pyplot module provides the function plt.plot() to create line plots. You provide x-values and y-values, and pyplot draws points connected by lines. Common options include marker, linestyle, color, label, and axis/figure controls (plt.xlabel, plt.ylabel, plt.title, plt.legend, plt.grid). For time series, use date-aware x-values and formatters.

Typical workflow (short code example)

import matplotlib.pyplot as plt
# sample data
x = [1, 2, 3, 4, 5]
y = [30, 31, 29, 32, 33]

plt.figure(figsize=(8,4))
plt.plot(x, y, marker='o', linestyle='-', color='C0', label='Temperature (°C)')
plt.xlabel('Day')
plt.ylabel('Temp (°C)')
plt.title('Daily Temperature')
plt.grid(True)
plt.legend()
plt.show()

Advanced features

  • Multiple lines: call plt.plot() multiple times or pass multiple y-series to compare series on same axes; use plt.legend().
  • Markers and line styles: choose markers ('o', 's', '^') and line styles ('-', '--', ':') for readability.
  • Error bars: use plt.errorbar() to show measurement uncertainty.
  • Smoothing: compute moving averages and plot original and smoothed series to reduce noise.
  • Filled regions: plt.fill_between() highlights ranges (e.g., confidence bands).
  • Dates & times: convert to pandas datetime or matplotlib.dates and format x-axis for readable time labels.
  • Save figure: plt.savefig('plot.png', dpi=300).

When to use line plots: trends over time, continuous measurements (temperature, stock prices, sensor outputs), comparing similar metrics across the same x-axis, visualising derivatives (rate of change), and showing seasonal patterns.

📌 Examples
  • Stock market prices over days or minutes — shows upward/downward trends and volatility.
  • Daily temperature readings for a week/month — observes warming or cooling trends.
  • Students' test scores across terms — track improvement or decline over time.
  • Website traffic (visitors per day) — identify peaks, drops and growth patterns.
  • Heart rate monitor readings — continuous sensor data showing health events or exercise intensity.
  • CPU and memory usage of a server over time — compare multiple series to find resource bottlenecks.
🧮 Formulas
  1. \[Equation of a straight line: y = m*x + c (m = slope\]
    \[c = intercept).\]
  2. \[Slope between two points (x1,y1) and (x2,y2): m = (y2 - y1) / (x2 - x1).\]
  3. \[Percentage change: % change = (new - old) / old * 100.\]
  4. \[Simple moving average (window size k): SMA_t = (y_{t} + y_{t-1} + ... + y_{t-k+1}) / k.\]
  5. \[Discrete derivative (approx. rate of change): dy/dx ≈ (y_{i+1} - y_{i}) / (x_{i+1} - x_{i}).\]
💻6

Scatter Plots

💻 COMPUTER SCIENCE / IT

Scatter Plots

Key Point: Pearson correlation coefficient (r): r = [ sum((xi - x̄)(yi - ȳ)) ] / sqrt( sum((xi - x̄)^2) * sum((yi - ȳ)^2) )

What is a scatter plot?
A scatter plot is a two-dimensional chart that displays values for two variables as points (x, y). Each point represents an observation; the horizontal axis is one variable and the vertical axis is the other. Scatter plots show relationships (correlation), clusters, trends, and outliers between numeric variables.

Why use scatter plots in data-visualisation (Pyplot)?
They are ideal for exploring whether two variables are related (positively, negatively, or not), checking linearity or curvature, detecting groups/clusters, and spotting outliers. Matplotlib's pyplot makes it easy to draw and customize scatter plots.

Key pyplot usage (concise)

import matplotlib.pyplot as plt
plt.scatter(x, y, s=50, c='blue', marker='o', alpha=0.7)
plt.xlabel('X label')
plt.ylabel('Y label')
plt.title('Scatter plot')
plt.show()
Important parameters: s (size), c (color or array for colormap), cmap (colormap), marker (shape), alpha (transparency), edgecolors. Use plt.colorbar() when c is numeric to show scale.

How to interpret
- Positive correlation: points slope upward.
- Negative correlation: points slope downward.
- No clear slope: weak or no correlation.
- Clusters: possible subgroups.
- Outliers: points far from others.
Also check spread (heteroscedasticity) and non-linear patterns.

Enhancements
- Color or marker by category to show groups.
- Use point size to encode a third variable.
- Add a best-fit (regression) line to summarise trend.
- Apply jitter for overlapping discrete values, or use alpha to show density.
- For dense data, consider 2D histogram or hexbin to show density.

📌 Examples
  • Height vs Weight of students — see how weight tends to increase with height and detect outliers (very heavy/light for height).
  • Hours studied vs Exam score — identify positive correlation and diminishing returns.
  • Temperature vs Ice-cream sales — positive relation, seasonal clustering and possible nonlinearity.
  • Advertising spend vs Sales — check whether higher advertising correlates with higher sales and find diminishing returns or outliers.
  • Engine size vs Fuel consumption — often positive correlation with possible clusters by car type.
🧮 Formulas
  1. \[Pearson correlation coefficient (r): r = [ sum((xi - x̄)(yi - ȳ)) ] / sqrt( sum((xi - x̄)^2) * sum((yi - ȳ)^2) )\]
  2. \[Simple linear regression line: y = m x + b\]
    \[where slope m = sum((xi - x̄)(yi - ȳ)) / sum((xi - x̄)^2) and intercept b = ȳ - m x̄\]
  3. \[Covariance: cov(x,y) = (1/(n-1)) * sum((xi - x̄)(yi - ȳ))\]
  4. \[Coefficient of determination (for simple linear regression): R^2 = 1 - SSE/SST = r^2 (when model is simple linear)\]
  5. \[Residual Sum of Squares (SSE): SSE = sum((yi - ŷi)^2)\]
    \[Total Sum of Squares (SST): SST = sum((yi - ȳ)^2)\]
💻7

Bar Charts

💻 COMPUTER SCIENCE / IT

Bar Charts

Key Point: Positions for grouped bars: x = np.arange(n) where n = number of categories.

What is a Bar Chart?
A bar chart (or bar graph) is a categorical data visualization that represents discrete items (categories) as rectangular bars. The length (or height) of each bar is proportional to the value or frequency of the category. Bar charts are ideal for comparing values across categories.

Why use bar charts?

  • Clear comparison of categories (e.g., marks per student, sales per month).
  • Easy to read and interpret.
  • Flexible: vertical, horizontal, grouped, stacked, with error bars, annotated values.

Creating Bar Charts with pyplot (matplotlib)

Typical imports:

import matplotlib.pyplot as plt
import numpy as np

Basic vertical bar chart:

labels = ['A', 'B', 'C']
values = [23, 45, 12]
plt.bar(labels, values, color='skyblue')
plt.xlabel('Category')
plt.ylabel('Value')
plt.title('Basic Bar Chart')
plt.show()

Common variants (short descriptions):

  • Horizontal bars – use plt.barh(labels, values) when category names are long.
  • Grouped (side-by-side) bars – compare multiple series; compute x positions using np.arange and offsets.
  • Stacked bars – show subparts of a whole; use bottom parameter to place bars on top of each other.
  • Error bars – show uncertainty using yerr= (e.g., standard error) and capsize.
  • Annotations – label bar heights using plt.text for clarity.

Best practices

  • Label axes and title, include legend when multiple series are present.
  • Rotate x-tick labels if they overlap (e.g., plt.xticks(rotation=45)).
  • Choose distinct colors or hatch patterns for multiple series.
  • Use plt.tight_layout() before plt.show() to avoid clipping.
  • Export figure with plt.savefig('chart.png', dpi=300) if needed.

Short code examples for variants

Grouped bars:

labels = ['Jan', 'Feb', 'Mar']
x = np.arange(len(labels))
width = 0.35
plt.bar(x - width/2, sales_A, width, label='Product A')
plt.bar(x + width/2, sales_B, width, label='Product B')
plt.xticks(x, labels)
plt.legend()

Stacked bars:

plt.bar(x, part1, width, label='Part 1')
plt.bar(x, part2, width, bottom=part1, label='Part 2')

Error bars and annotations:

plt.bar(x, means, yerr=errors, capsize=5)
for i, v in enumerate(means):
    plt.text(i, v + error_offset, str(v), ha='center')
📌 Examples
  • Exam marks per subject: compare average marks of Class 12 students across subjects (Maths, Physics, Chemistry).
  • Monthly sales: show sales amount for each month to spot seasonal trends.
  • Population by state: display population per state to compare sizes.
  • Survey results: show counts/percentages for preferred options (Yes, No, Maybe).
  • Browser market share: compare percentage share of different web browsers.
🧮 Formulas
  1. \[Positions for grouped bars: x = np.arange(n) where n = number of categories.\]
  2. \[Offset positions for series i (width = bar width): position_i = x + (i - (k-1)/2) * width\]
    \[where k = number of series.\]
  3. \[Stacked bar bottom calculation: bottom_i = sum of all previous series heights at that category (cumulative sum).\]
  4. \[Convert counts to percentages: percent = (count / total) * 100.\]
  5. \[Standard error for error bars (if using sample std): stderr = np.std(values\]
    \[ddof=1) / sqrt(len(values)).\]
💻8

Histograms

💻 COMPUTER SCIENCE / IT

Histograms

Key Point: Frequency for a bin: f = number of observations in that bin.

What is a histogram?
A histogram is a graphical representation that groups numeric data into continuous intervals (called bins) and shows the frequency (count) of data points that fall into each bin as bars. Unlike bar charts (which compare categorical values), histograms display the distribution of a continuous variable.

Components:

  • Bins (intervals): contiguous ranges that partition the data axis.
  • Bin edges: the boundaries of each bin.
  • Bar height: frequency (count) or density (normalized height) of observations in the bin.
  • Bin width: size of each interval; choice of bin width affects appearance and interpretation.

When to use: Use histograms to explore the shape of a distribution (symmetry, skewness), detect multimodality, spot outliers, and check spread or concentration of values.

Matplotlib (pyplot) basics: In Python's matplotlib.pyplot the main function is plt.hist(). Common parameters:

  • x: data array
  • bins: number of bins or explicit bin edges
  • range: lower and upper limits
  • density=True: plot probability density instead of counts
  • cumulative=True: cumulative histogram
  • histtype: 'bar', 'barstacked', 'step', 'stepfilled'
  • rwidth, edgecolor, alpha, orientation

Example code (basic):

import matplotlib.pyplot as plt
scores = [45, 67, 78, 90, 56, 67, 72, 88, 91, 54, 60, 70]
plt.hist(scores, bins=8, color='skyblue', edgecolor='black')
plt.xlabel('Score')
plt.ylabel('Frequency')
plt.title('Histogram of Exam Scores')
plt.show()

Interpretation tips: Look at bar heights to see where data clusters. Use density=True when comparing datasets of different sizes. Try several bin counts or automatic rules (Sturges/Scott/Freedman–Diaconis) to avoid misleading shapes.

Common pitfalls: Choice of bins can hide or create apparent modes; very wide bins oversmooth the data, very narrow bins create noisy charts. Always label axes and indicate whether heights are counts or densities.

📌 Examples
  • Exam scores: Show distribution of students' marks to see clustering (fail/pass ranges) and identify outliers.
  • Daily temperatures: Visualize frequency of temperature ranges over a month to understand climate patterns.
  • Transaction amounts: Analyze customer purchase amounts to see common spending brackets.
  • Ages of a population sample: See age groups and detect concentration in particular decades.
  • Sensor readings: Inspect distribution and check for measurement bias or unexpected spikes.
🧮 Formulas
  1. \[Frequency for a bin: f = number of observations in that bin.\]
  2. \[Relative frequency: rf = f / N (N = total number of observations).\]
  3. \[Density (height when normalized): density = f / (N * bin_width)\]
    \[This makes area under histogram = 1.\]
  4. \[Cumulative frequency at bin k: CF_k = sum_{i=1..k} f_i.\]
  5. \[Sturges' rule (recommend bins): k = ceil(log2(N) + 1).\]
  6. \[Scott's rule (bin width h): h = 3.5 * sigma / N^{1/3}\]
    \[where sigma = sample standard deviation.\]
💻9

Pie Charts

💻 COMPUTER SCIENCE / IT

Pie Charts

Key Point: Percentage of category i = (value_i / total) × 100

What is a pie chart?
A pie chart is a circular statistical graphic divided into slices to illustrate numerical proportions. Each slice represents a category's contribution to the whole; the slice angle (and area) is proportional to the category value.

When to use: Use pie charts to show relative proportions (percentages) of a small number (typically 2–7) of categories. They are best when you want an immediate visual sense of part-to-whole relationships.

Using Pyplot (matplotlib)
Matplotlib's pyplot provides plt.pie(...) to draw pie charts. Common parameters include:

  • labels: names for each slice
  • autopct: format string for percent labels (e.g. '%1.1f%%')
  • explode: tuple of offsets to “pull out” slices
  • startangle: rotation start (degrees)
  • colors: list of slice colors
  • shadow: boolean for drop shadow

Important tips: always call plt.axis('equal') to ensure the pie is a circle; avoid too many slices; combine very small categories into "Other" to keep the chart readable. Values must be non-negative (zeros omitted).

Minimal example (Pyplot)

import matplotlib.pyplot as plt
sizes = [30, 45, 25]
labels = ['Category A', 'Category B', 'Category C']
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, explode=(0.1,0,0))
plt.axis('equal')  # keep as circle
plt.show()
📌 Examples
  • School budget allocation: percentages of budget spent on salaries, infrastructure, books, and activities.
  • Class survey results: favorite programming languages among students (Python, Java, C++, JavaScript).
  • Market share: percent share of smartphone manufacturers in a quarter.
  • Election exit poll: proportion of voters preferring each candidate/party.
  • Expense breakdown for a project: development, testing, marketing, and contingency.
🧮 Formulas
  1. \[Percentage of category i = (value_i / total) × 100\]
  2. \[Angle of slice (degrees) = (value_i / total) × 360\]
  3. \[Value from percentage: value_i = (percentage_i / 100) × total\]
💻10

Subplots and Layout Management

💻 COMPUTER SCIENCE / IT

Subplots and Layout Management

Key Point: Total subplots = nrows * ncols

What are subplots?
A subplot is an individual Axes (plot area) inside a larger Figure. Subplots let you display multiple related charts together for easy comparison (for example, a 2x2 grid of plots).

Creating subplots
The most common method is fig, axes = plt.subplots(nrows, ncols, figsize=(w,h), sharex=False, sharey=False). This returns a Figure object and an array (or single object) of Axes. You can also use plt.subplot() to create one subplot at a time, or matplotlib.gridspec for complex layouts.

Indexing and iterating
When nrows>1 or ncols>1, axes is a 2D array: axes[row, col]. If you need a flat iterator, use axes.ravel() or axes.flatten().

Sharing axes
Use sharex=True or sharey=True so subplots share the same axis limits and ticks, making comparisons easier and reducing clutter.

Spacing & layout management
Matplotlib provides several ways to adjust spacing between subplots:

  • plt.tight_layout() — automated spacing that reduces overlaps.
  • fig.tight_layout() or fig.subplots_adjust(left, right, top, bottom, hspace, wspace) — manual fine control, where hspace and wspace control vertical and horizontal spacing as fractions of subplot sizes.
  • fig.constrained_layout = True or plt.subplots(..., constrained_layout=True) — alternative automatic layout that handles legends, colorbars and labels more reliably in many cases.
  • GridSpec and subplot2grid — for non-uniform or nested subplot arrangements (different subplot sizes and spanning rows/cols).

Figure size and resolution
Use figsize=(width_inches, height_inches) and dpi to control output size and resolution. Higher DPI produces more pixels for the same physical size.

Common workflow
1) Create Figure and Axes with plt.subplots.
2) Plot on each Axes (axes[i,j].plot(...)).
3) Adjust labels, legends, and limits.
4) Call fig.tight_layout() or fig.subplots_adjust(...) to fix spacing.
5) Save with fig.savefig('name.png', dpi=150).

Small example (concept)

import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 2, figsize=(10, 6), sharex=True)
axes[0,0].plot(x1, y1)
axes[0,1].bar(x2, y2)
axes[1,0].scatter(x3, y3)
axes[1,1].hist(data)
fig.tight_layout()
plt.show()

Tips

  • Use sharex/sharey for time-series panels to align ticks and zoom behavior.
  • Use suptitle for a common title: fig.suptitle('Overall title').
  • Reserve constrained_layout when adding colorbars or complex annotations.
  • When saving, ensure bbox_inches='tight' or call tight_layout() before saving to avoid clipped labels.
📌 Examples
  • Dashboard for stock analysis: 2x2 grid where top-left is price over time (line), top-right is trading volume (bar), bottom-left is moving averages (multiple lines), bottom-right is histogram of daily returns. Use sharex=True to align dates.
  • IoT sensor monitoring: 3 stacked subplots (3 rows, 1 column) showing temperature, humidity and pressure over the same time axis. Use sharex=True so cursor/time selection maps across plots.
  • Exam performance: 1 row x 3 columns comparing subject-wise marks distributions. Left: boxplot for Math; center: boxplot for Physics; right: boxplot for Computer Science. Use consistent y-limits for direct comparison.
  • Weather report layout: a larger left subplot (spanning rows) for temperature heatmap and two smaller right subplots for wind speed and rainfall. Use GridSpec to create a 2x2 layout with the left plot spanning both rows.
  • Inset plot: show a main scatter plot with a smaller zoomed-in subplot placed inside the main axes using 'axes.inset_axes' (or add_axes) for a detailed view.
🧮 Formulas
  1. \[Total subplots = nrows * ncols\]
  2. \[Index mapping (1-based to 0-based row/col): row = (index - 1) // ncols\]
    \[col = (index - 1) % ncols\]
  3. \[Figure pixel dimensions: width_pixels = figsize_width_in_inches * dpi\]
    \[height_pixels = figsize_height_in_inches * dpi\]
  4. \[Spacing control: effective horizontal spacing = wspace * average_subplot_width\]
    \[vertical = hspace * average_subplot_height (wspace and hspace are fractions used by subplots_adjust)\]
💻11

Plot Customization and Annotation

💻 COMPUTER SCIENCE / IT

Plot Customization and Annotation

Key Point: Percent change between two values: percent_change = (new - old) / old * 100

What it is: Plot customization and annotation in matplotlib.pyplot means changing how a plot looks (colors, line styles, markers, fonts, layout) and adding explanatory text/graphics (labels, titles, legends, arrows, boxes) so the chart is clear and informative.

Main goals: (1) Make data easy to read and interpret, (2) highlight important values/events, (3) make plots publication- or presentation-ready.

Common customization elements and functions:

  • Figure & size: plt.figure(figsize=(w,h), dpi=...)
  • Styles: plt.style.use('seaborn') or plt.rcParams to set global defaults
  • Line/marker properties: color='r', linestyle='--', linewidth=2, marker='o', markersize=6, alpha=0.8
  • Titles and labels: plt.title('Title', fontsize=...), plt.xlabel(...), plt.ylabel(...)
  • Axis limits and ticks: plt.xlim(a,b), plt.ylim(c,d), plt.xticks([...], rotation=...), plt.yticks(...)
  • Grid and background: plt.grid(True), facecolor, axis('equal')
  • Legend: plt.legend(loc='best') or ax.legend(), labels via label='name' in plot()
  • Layout: plt.subplot(), plt.subplots(nrows,ncols), fig.tight_layout()
  • Saving: plt.savefig('file.png', dpi=300, bbox_inches='tight')

Annotations (explain and point to data):

  • Text: plt.text(x,y,'note', fontsize=..., bbox=dict(boxstyle='round', fc='w')) places text at data coordinates.
  • Annotate (with arrow): plt.annotate('peak', xy=(x,y), xytext=(x2,y2), arrowprops=dict(arrowstyle='->', color='k')) — draws an arrow from text to point.
  • Highlighting: ax.axhline(), ax.axvline(), ax.axvspan(), ax.axhspan() to mark thresholds or ranges.

Best practices: Use readable fonts and sizes, choose contrasting colors, rotate x-tick labels if crowded, add a legend when multiple series exist, annotate only the most important points to avoid clutter, and always label axes with units.

How annotation is used: Add context (e.g., events on a timeline), show exact values, call out maxima/minima or anomalies, and explain data segments (e.g., shaded area for target range).

📌 Examples
  • Temperature trend for a week (line plot): plot day vs temperature, set title, xlabel/ylabel, grid, mark and annotate the highest temperature with plt.annotate('Max: 42°C', xy=(day_index,42), xytext=(day_index+0.5,40), arrowprops={'arrowstyle':'->'})
  • Monthly sales (bar chart): bar chart of months vs sales, add value labels on top of each bar using for loop with plt.text, highlight the best month with a different color and a bounding box.
  • Stock price with event (candlesticks or line): plot time vs price, add vertical line ax.axvline(date_of_event, color='r', linestyle='--') and annotate the event ('News release') with plt.annotate(...).
  • Student marks comparison (grouped bar): use different colors and a legend for subjects, rotate x-ticks for student names, and annotate average scores using ax.hlines() and text.
  • Sales growth with trendline: scatter of time vs sales, compute and plot linear regression y=mx+c to show trend, annotate slope and R² on the plot.
🧮 Formulas
  1. \[Percent change between two values: percent_change = (new - old) / old * 100\]
  2. \[Moving average (window size k): MA_t = (1/k) * sum_{i=t-k+1}^{t} x_i\]
  3. \[Linear regression (best-fit line): y = m x + c\]
    \[where m = (N sum(xy) - sum(x) sum(y)) / (N sum(x^2) - (sum(x))^2) and c = (sum(y) - m sum(x)) / N\]
  4. \[Annotating coordinates: use the data point (x,y) directly\]
    \[for display offsets use xytext=(x_text\]
    \[y_text) in data or text coordinates\]
💻12

Axes, Limits and Ticks

💻 COMPUTER SCIENCE / IT

Axes, Limits and Ticks

Key Point: Uniform tick step: step = (max - min) / (n - 1) → ticks = min + step * np.arange(n)

Overview: In Matplotlib's pyplot, the axes are the coordinate area that displays data (x-axis and y-axis). Limits control the range of data shown on each axis. Ticks are the small marks (and their labels) along the axes that indicate values. Proper control of axes, limits and ticks is essential for clear, accurate visualisation.

Axes: The axes include:

  • Labels (xlabel, ylabel): describe what each axis represents.
  • Spines: the lines denoting the axis boundaries (left, right, bottom, top).
  • Aspect: the scaling between x and y units (equal, auto, or a numeric ratio).

Limits: Set the visible data range with methods:

  • pyplot: plt.xlim(left, right), plt.ylim(bottom, top)
  • object-oriented: ax.set_xlim(left, right), ax.set_ylim(bottom, top)

Use limits to zoom, remove outliers, or focus on a region.

Ticks: Control where tick marks appear and how they are labeled.

  • Set locations: ax.set_xticks([list_of_positions]), ax.set_yticks([...])
  • Set labels: ax.set_xticklabels(['Jan','Feb',...]) or plt.xticks(positions, labels, rotation=45)
  • Tick appearance: ax.tick_params(axis='x', rotation=45, labelsize=10, length=6)
  • Minor ticks: use locators from matplotlib.ticker, e.g. MultipleLocator, AutoLocator, LogLocator.
  • Formatters: FuncFormatter or DateFormatter to control label formatting.

Common patterns / tips:

  • Compute uniform ticks with numpy: np.linspace(xmin, xmax, n).
  • For date/time axes, use matplotlib.dates locators/formatters and rotate labels to avoid overlap.
  • For log-scale data use ax.set_xscale('log') and LogLocator to place ticks at powers of 10.
  • To zoom programmatically, set limits tight around the region of interest and optionally add a rectangle on an inset axis.

Short code example:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator, AutoMinorLocator
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
# Limits
ax.set_xlim(0, 8)
ax.set_ylim(-1.1, 1.1)
# Major ticks every 2 units, minor ticks every 0.5
ax.xaxis.set_major_locator(MultipleLocator(2))
ax.xaxis.set_minor_locator(MultipleLocator(0.5))
ax.tick_params(which='major', length=7)
ax.tick_params(which='minor', length=3)
ax.set_xlabel('Time (s)')
ax.set_ylabel('Amplitude')
plt.show()

When to adjust: change axes/limits/ticks to improve readability, remove whitespace, highlight trends, or correctly present nonuniform scaling (e.g., log scale for power-law data).

📌 Examples
  • Daily temperature: x-axis = dates (use DateFormatter and rotate labels), set x-limits to a month and ticks at weekly intervals.
  • Stock prices: zoom into last 30 days using plt.xlim(); use minor ticks for intra-day hours and major ticks for days.
  • Earthquake magnitudes: plot histogram or scatter on log scale with ax.set_xscale('log') and LogLocator so ticks are at 10^k.
  • ECG / biomedical signal: use tight x-limits to inspect a single heartbeat; use dense minor ticks for ms resolution.
  • Geographic scatter: set aspect='equal' so units on x and y are comparable; set custom ticks for latitude/longitude gridlines.
🧮 Formulas
  1. \[Uniform tick step: step = (max - min) / (n - 1) → ticks = min + step * np.arange(n)\]
  2. \[Linspace ticks: ticks = np.linspace(min\]
    \[max\]
    \[n)\]
  3. \[Log-scale ticks (powers of 10): ticks = 10 ** np.arange(floor(log10(min))\]
    \[ceil(log10(max)) + 1)\]
  4. \[Normalization (mapping value to axis fraction): x_norm = (x - xmin) / (xmax - xmin) (useful for annotations/insets)\]
  5. \[Aspect ratio (to preserve unit scaling): aspect = (xmax - xmin) / (ymax - ymin) (set via ax.set_aspect(aspect))\]
🗺️13

Colors, Styles and Colormaps

💻 COMPUTER SCIENCE / IT

Colors, Styles and Colormaps

Key Point: Normalization (map scalar to [0,1]): t = (value - vmin) / (vmax - vmin) (then clamp t to [0,1])

Overview
In Matplotlib's Pyplot, colors and styles control appearance of plotted objects (lines, markers, patches). Colormaps map numeric (scalar) data to colors and are used for heatmaps, images and value-encoded scatter plots.

Specifying colors
You can specify colors in several ways:

  • Named colors: color='red', many CSS4 names supported
  • Hex code: color='#1f77b4'
  • RGB(A) tuples with values 0–1: color=(0.1,0.2,0.5)
  • RGB 0–255 scaled to 0–1: (r/255,g/255,b/255)
  • Grayscale string: color='0.75' (0 black → 1 white)
  • Cycle colors: 'C0','C1',... use Matplotlib's default cycle

Line and marker styles
Common style options when plotting: linestyle (or ls) values: '-','--','-.',':'; linewidth (or lw); marker symbols: 'o','s','^','.'; markersize; alpha for transparency. You can combine in a format string: plt.plot(x,y,'r--o') for red dashed line with circle markers.

Colormaps
Colormaps are functions that map normalized scalar values (0→1) to colors (RGBA). Use them where color encodes data magnitude. Types of colormaps:

  • Sequential: for ordered data from low→high (e.g., 'viridis', 'plasma', 'inferno', 'magma', 'cividis').
  • Diverging: emphasize deviation from a midpoint (e.g., 'coolwarm', 'RdYlBu', 'seismic').
  • Qualitative (categorical): for nominal categories (e.g., 'tab10', 'Set1').
Apply with functions: imshow(...,cmap='viridis'), scatter(...,c=values,cmap='viridis',vmin=...,vmax=...), and add a colorbar plt.colorbar(). Use matplotlib.colors.Normalize or LogNorm to control mapping.

Normalization concept
To color a value, map it to the unit interval: t=(value - vmin)/(vmax - vmin) (clamped to [0,1]). Then colormap(t) → RGBA.

Good practices
Use perceptually-uniform colormaps (e.g., viridis, cividis) for continuous data; use diverging colormaps when highlighting positive/negative deviations and set midpoint explicitly; use qualitative maps for categories. Always include a colorbar and labels, and consider colorblind-safe palettes.

📌 Examples
  • Line styles (different series): plt.plot(x1,y1, color='C0', linestyle='-', linewidth=2, label='Series A') plt.plot(x2,y2, color='C1', linestyle='--', marker='o', markersize=4, label='Series B')
  • Scatter colored by value: plt.scatter(x, y, c=values, cmap='viridis', s=40, edgecolor='k') plt.colorbar(label='Measured value')
  • Heatmap / image: plt.imshow(matrix, cmap='inferno', aspect='auto') plt.colorbar(label='Intensity')
  • Diverging map (difference from baseline): norm = mpl.colors.TwoSlopeNorm(vmin=-10, vcenter=0, vmax=10) plt.imshow(diff, cmap='RdYlBu', norm=norm) plt.colorbar()
  • Categorical colors for bars: colors = plt.get_cmap('tab10')(range(n_categories)) plt.bar(categories, heights, color=colors)
🧮 Formulas
  1. \[Normalization (map scalar to [0,1]): t = (value - vmin) / (vmax - vmin) (then clamp t to [0,1])\]
  2. \[Convert normalized float RGB to 0-255 integer: r255 = int(r_float * 255)\]
    \[g255 = int(g_float * 255)\]
    \[b255 = int(b_float * 255)\]
  3. \[Hex from 0-255 ints (pseudo): hex = '#' + format(r255, '02x') + format(g255, '02x') + format(b255, '02x')\]
  4. \[Convert 0-255 to float RGB: r_float = r255 / 255.0\]
    \[g_float = g255 / 255.0\]
    \[b_float = b255 / 255.0\]
💻14

Saving and Exporting Figures

💻 COMPUTER SCIENCE / IT

Saving and Exporting Figures

Key Point: pixels_width = inches_width × dpi (gives horizontal pixel count of saved image)

What and why: Saving and exporting figures in Pyplot means writing the plotted figure from memory to an external file so it can be used in reports, web pages, presentations or printed materials. Pyplot provides plt.savefig() and the object-oriented equivalent fig.savefig() with many options to control format, size, resolution and layout.

Key concepts:

  • Raster vs Vector formats: PNG, JPG are raster images (pixel based). SVG, PDF are vector formats (scale without loss of quality) — prefer vector for line plots and print-quality diagrams.
  • DPI (dots per inch): controls image resolution. Higher DPI gives more pixels and sharper printed output.
  • Figure size: figure physical size in inches is set by figsize=(width, height). Pixels = inches × DPI.
  • Tight layout & bounding box: use plt.tight_layout() or bbox_inches='tight' to avoid clipped labels and legends.
  • Transparency and background: use transparent=True for overlays; set facecolor and edgecolor for custom backgrounds.

Common parameters of savefig:

  • fname — filename or path, e.g. 'plot.png' or 'folder/plot.svg'
  • dpi — resolution in dots per inch (integer)
  • format — file format, e.g. 'png', 'pdf', 'svg', 'jpg'
  • bbox_inches — usually 'tight' to trim extra whitespace
  • pad_inches — padding around the figure when using 'tight'
  • transparent — True/False for background transparency

Basic examples (code):

import matplotlib.pyplot as plt
x = [1,2,3]
y = [2,4,1]
plt.plot(x,y)
plt.title('Sample')
plt.tight_layout()            # prevent clipping
plt.savefig('sample_plot.png', dpi=150, bbox_inches='tight')
plt.close()

Saving multiple formats and high-quality export:

fig = plt.figure(figsize=(6,4))
# plotting code...
for fmt in ['png','pdf','svg']:
    fig.savefig(f'figure_name.'+fmt, dpi=300, bbox_inches='tight')
plt.close(fig)

Practical tips:

  • Choose SVG/PDF for publication and PNG for raster web images.
  • Set figsize and dpi to control final pixel dimensions (pixels = inches × dpi).
  • Always call plt.tight_layout() or use bbox_inches='tight' to ensure labels/legends are not clipped.
  • Close figures with plt.close() when creating many figures to free memory.

Using these options correctly ensures the exported figure appears crisp, correctly sized, and usable in different contexts (web, print, slides).

📌 Examples
  • School report chart: Plot students' average marks for each subject and save as 'marks_report.png' at 300 dpi for clear inclusion in a PDF report. Code sketch: plt.bar(subjects, marks); plt.tight_layout(); plt.savefig('marks_report.png', dpi=300, bbox_inches='tight')
  • Website interactive graphics: Save the same plot as 'marks_chart.svg' to embed in a webpage so it scales cleanly at any display size. Use fig.savefig('marks_chart.svg') (vector format preserves sharp lines and text).
  • Presentation slide: Save a temperature trend line plot as a high-resolution PNG with transparent background to overlay on a slide: plt.savefig('temp_trend.png', dpi=200, transparent=True, bbox_inches='tight')
🧮 Formulas
  1. \[pixels_width = inches_width × dpi (gives horizontal pixel count of saved image)\]
  2. \[pixels_height = inches_height × dpi (gives vertical pixel count)\]
  3. \[aspect_ratio = width / height (preserved when saving unless you change figsize or resize)\]
  4. \[file_size (approx) ∝ dpi² × complexity (higher dpi increases raster file size roughly with the square of dpi)\]
⚙️15

Working with Data Sources

💻 COMPUTER SCIENCE / IT

Working with Data Sources

Key Point: Mean: μ = (Σ x_i) / n

Working with Data Sources means acquiring, inspecting, cleaning and preparing data so it can be visualised correctly with Pyplot. Data sources include files (CSV, Excel), structured formats (JSON), databases (SQL), web APIs, and web pages (scraping). The typical workflow is: acquire & connect → inspect → clean/transform → aggregate/index → visualise → save/export.

Key steps and practical tips:

  • Acquisition: Use pandas.read_csv, read_excel, read_json, read_sql or requests for APIs. For large files, use chunksize or iterate streams.
  • Inspecting data: Check columns, data types and basic stats using df.head(), df.info(), df.describe(). Look for missing values, wrong dtypes (e.g., dates read as strings) and outliers.
  • Cleaning: Handle missing values (dropna, fillna, interpolation), convert types with astype and pd.to_datetime, remove duplicates (drop_duplicates), trim strings and handle inconsistent categories (use str.strip().str.lower()).
  • Transforming & aggregating: Create derived columns (e.g., month/year from date), group and aggregate (groupby), pivot tables (pivot_table), normalise or scale if comparing metrics.
  • Performance: Specify dtypes, read only needed columns with usecols, set parse_dates at read time, convert text columns to category for few unique values, and process large data in chunks.
  • Reproducibility & security: Record data source paths/URLs and query parameters, cache API responses, and follow privacy rules when using personal data.
  • Preparing for plotting: Aggregate data to the correct granularity (e.g., daily → monthly), sort by date or category, handle missing timepoints (fill zeros or use interpolation), and scale axes or use log scale for skewed distributions.

Common pandas examples (inline): df = pd.read_csv('sales.csv', parse_dates=['date'], usecols=['date','region','sales']); resp = requests.get(api_url).json(); df = pd.json_normalize(resp); conn = sqlite3.connect('data.db'); df = pd.read_sql('SELECT date,score FROM tests', conn, parse_dates=['date']).

📌 Examples
  • Load a CSV of daily sales and create monthly totals: read CSV with pd.read_csv('sales.csv', parse_dates=['date']), set df['month']=df['date'].dt.to_period('M'), monthly = df.groupby('month')['sales'].sum().reset_index().
  • Get JSON data from a public API (e.g., weather or COVID): r = requests.get(url); payload = r.json(); df = pd.json_normalize(payload['records']); convert date fields and aggregate by region.
  • Read a multi-sheet Excel workbook of students' marks, combine sheets: pd.read_excel('marks.xlsx', sheet_name=None) returns a dict of DataFrames; concatenate with pd.concat and clean column names.
  • Query a SQL database for large tables with a filter to reduce size: pd.read_sql('SELECT date,region,sales FROM sales WHERE year>=2020', conn, parse_dates=['date']) and then sample or aggregate before plotting.
  • Handle missing values before plotting: df['score']=df['score'].fillna(df['score'].mean()) or forward-fill time series with df['value'].interpolate() for smoother line plots.
🧮 Formulas
  1. \[Mean: μ = (Σ x_i) / n\]
  2. \[Median: middle value after sorting (or average of two middle values if n even)\]
  3. \[Sample variance: s² = Σ (x_i - μ)² / (n - 1)\]
    \[Standard deviation: s = sqrt(s²)\]
  4. \[Min-max normalization: x' = (x - min(x)) / (max(x) - min(x)) — scales values to [0,1]\]
  5. \[Z-score (standard score): z = (x - μ) / σ — measures how many std devs a point is from mean\]
  6. \[Percent change: pct_change = (new - old) / old * 100\]
📊16

Data Preprocessing for Visualization

💻 COMPUTER SCIENCE / IT

Data Preprocessing for Visualization

Key Point: Mean: μ = (1/n) * Σ(x_i)

What it is: Data preprocessing for visualization is the set of steps that converts raw, messy data into a clean, consistent, and appropriately scaled form so that charts and plots accurately reveal patterns and insights. Good preprocessing improves readability, prevents misleading charts, and makes comparisons fair.

Key steps:

  • Inspect & clean: check data types, remove duplicate rows, fix typos and inconsistent categories.
  • Handle missing values: drop rows/columns, or impute (mean/median/mode), or use forward/backward fill for time series.
  • Detect & treat outliers: identify with IQR or z-scores and either remove, cap (winsorize), or keep with annotation depending on context.
  • Scale & transform: normalize (min–max) or standardize (z-score) numeric features; use log or power transforms for skewed distributions.
  • Encode categorical variables: label-encode ordinal data; one-hot encode nominal categories; group rare categories into "Other".
  • Aggregate & resample: summarize by groups (sum, mean, count) and resample time-series (e.g., daily → monthly) to reduce clutter.
  • Smooth & denoise: moving averages, rolling median, or filtering for sensor/time-series data to reveal trends.
  • Feature engineering & parsing: extract components (year, month, weekday) from dates; create rates or ratios to make comparisons meaningful.

Why it matters for visualization: Visual plots depend on data scale, distribution and correctness. Without preprocessing, axes may be dominated by extreme values, categories may be split incorrectly, or time-series may show spurious noise. Preprocessing ensures that the chosen plot highlights the real story.

Good practice tips: always keep a copy of raw data, log each transformation, justify imputations and removals in captions/notes, and verify effects with diagnostic plots (histogram, boxplot) before final visualization.

📌 Examples
  • Retail sales dataset with missing daily sales: resample to monthly totals and impute small gaps with forward-fill for continuity before plotting a monthly revenue line chart.
  • Survey responses with 'Prefer not to say' and typos: standardize category labels, group rare answers into 'Other', then plot bar charts of response counts.
  • Sensor temperature readings with high-frequency noise: apply a 7-point moving average to smooth the time series, then plot the smoothed line to show trend.
  • Income distribution that is heavily right-skewed: apply log transformation before plotting a histogram so the distribution shape is clearer and bins are meaningful.
  • E-commerce dataset with product categories: one-hot encode categories or aggregate into top-10 categories + 'Other' to produce a clear bar chart of product counts.
🧮 Formulas
  1. \[Mean: μ = (1/n) * Σ(x_i)\]
  2. \[Median: the middle value after sorting (or average of two middle values if n is even)\]
  3. \[Min–max scaling (normalization) to [0,1]: x' = (x - min(x)) / (max(x) - min(x))\]
  4. \[Z-score (standardization): z = (x - μ) / σ\]
    \[where μ is mean and σ is standard deviation\]
  5. \[Interquartile Range (IQR): IQR = Q3 - Q1\]
    \[Common outlier thresholds: x < Q1 - 1.5·IQR or x > Q3 + 1.5·IQR\]
  6. \[Moving average (window w): MA_t = (1/w) * Σ_{i=t-w+1}^{t} x_i\]
📊17

Statistical and Summary Plots

💻 COMPUTER SCIENCE / IT

Statistical and Summary Plots

Key Point: Mean (average): mean = (1/n) * Σ xi

Statistical and summary plots are visual tools that summarize key properties of a dataset — central tendency, spread, shape of distribution and presence of outliers — so we can grasp patterns quickly. In the context of Pyplot (matplotlib.pyplot), these plots are used to convert raw numbers into interpretable visuals for analysis and decision making.

Common summary and statistical plots include histograms, box plots, bar charts of grouped summaries, violin plots, and density/KDE plots. Each plot emphasizes different aspects:

  • Histogram: shows the frequency distribution of a numeric variable and reveals skewness, modality, and approximate spread.
  • Box plot (box-and-whisker): summarizes median, quartiles (Q1, Q3), interquartile range (IQR) and outliers — useful for comparing distributions across groups.
  • Violin plot: combines a box plot with a kernel density estimate to show the full distribution shape and summary statistics.
  • Density (KDE) plot: gives a smoothed estimate of the distribution (useful when you want a continuous curve rather than discrete bins).
  • Bar plot of summary statistics: displays aggregated statistics (mean, median) for categories; useful for comparing group-level summaries.

When using Pyplot, typical workflow is: compute summary statistics (mean/median/quantiles/variance), then choose an appropriate plot to illustrate these statistics. For example, use a box plot to highlight outliers and spread, and a histogram or KDE to inspect modality and skew.

Interpretation tips:

  • Check skewness: a long tail to the right indicates positive skew, to the left indicates negative skew.
  • Compare spread using IQR and standard deviation — wider IQR or larger SD means more variability.
  • Outliers in box plots appear as points beyond the whiskers (commonly beyond 1.5 * IQR from Q1/Q3).
  • Multi-modal histograms (multiple peaks) suggest heterogeneous subgroups or mixed processes.
📌 Examples
  • Exam scores of a class: use a histogram to see score distribution, a box plot to compare male vs female score distributions, and compute mean/median to measure central tendency.
  • Daily sales of a store: use a KDE or histogram to check typical sales ranges and seasonality; use a box plot per weekday to compare variability between days.
  • Sensor temperature readings over a week: use a box plot to identify outlier spikes and a line plot with overlaid rolling mean to show trend.
  • House price dataset: use violin plots to compare price distributions between neighborhoods and bar plots of median price per neighborhood.
🧮 Formulas
  1. \[Mean (average): mean = (1/n) * Σ xi\]
  2. \[Median: middle value after sorting\]
    \[if n is even\]
    \[median = average of the two central values\]
  3. \[Mode: most frequent value(s) in the dataset\]
  4. \[Population variance: σ² = (1/N) * Σ (xi - μ)²\]
  5. \[Sample variance: s² = (1/(n-1)) * Σ (xi - x̄)²\]
  6. \[Standard deviation: σ = sqrt(variance) or s = sqrt(s²)\]
💻18

Interactivity and Dynamic Plots (Introductory)

💻 COMPUTER SCIENCE / IT

Interactivity and Dynamic Plots (Introductory)

Key Point: Slope between two points (trend line): m = (y2 - y1) / (x2 - x1)

Interactivity and dynamic plots make visualisations responsive to user actions and capable of changing over time. Instead of a static image, interactive plots allow zooming, panning, tooltips, and event-driven behavior (clicks, drags). Dynamic plots are updated programmatically to show live or animated data, useful for streaming sensors, simulations, or exploring parameter spaces.

Key ways to achieve interactivity in matplotlib/pyplot (introductory):

  • Built-in interactive toolbar: zoom, pan, save and basic cursors available in the GUI or notebook backends.
  • Interactive mode: plt.ion() enables non-blocking drawing. Use plt.pause(dt) to update the figure in a loop.
  • Event handling: connect callbacks with fig.canvas.mpl_connect for events like 'button_press_event', 'motion_notify_event', 'key_press_event'. Useful for clicking and dragging points or capturing coordinates.
  • Widgets: matplotlib.widgets provides Slider, Button, CheckButtons to let users change parameters and redraw plots without external UI frameworks.
  • Animations: matplotlib.animation.FuncAnimation creates smooth frame-by-frame updates; use blitting for performance.
  • Jupyter integration: %matplotlib notebook or ipywidgets enable richer interactivity inside notebooks. Libraries like mplcursors add hover tooltips easily.

Basic patterns (short examples):

# Simple live update using interactive mode
plt.ion()
fig, ax = plt.subplots()
line, = ax.plot([], [])
xdata, ydata = [], []
for i in range(100):
    xdata.append(i)
    ydata.append(math.sin(i/10.))
    line.set_data(xdata, ydata)
    ax.relim(); ax.autoscale_view()
    plt.pause(0.05)

# Animation using FuncAnimation
def update(frame):
    line.set_ydata(np.sin(x + frame/10.0))
    return line,
ani = FuncAnimation(fig, update, frames=200, interval=50, blit=True)

Practical tips:

  • Prefer FuncAnimation with blit for smoother, faster animations.
  • When streaming large volumes, update existing artists (lines, bars) instead of replotting everything.
  • Use event handlers for custom interactions (drag points, select regions), and widgets for parameter controls.
  • Test in the target environment: interactive behaviour differs between desktop GUI, Jupyter classic, and JupyterLab.

Why it matters: interactive and dynamic plots help users discover patterns, test hypotheses, and monitor systems in real time — turning static charts into exploratory tools.

📌 Examples
  • Live sensor monitoring: a line plot that updates every second to show temperature or CPU usage. Implement with plt.ion() or FuncAnimation to append new readings.
  • Interactive scatter: click a point to display its label or drag points to see how a fitted model responds. Use mpl_connect for click and motion events.
  • Parameter exploration: a sine wave whose frequency and amplitude are controlled by Slider widgets so students can see direct effects of parameter change.
  • Animated bar chart: show population or sales changes over time using FuncAnimation to step through years and animate bar heights.
  • Real-time histogram: update bins as streaming data arrives to visualise distribution shifts (use efficient buffer updates).
🧮 Formulas
  1. \[Slope between two points (trend line): m = (y2 - y1) / (x2 - x1)\]
  2. \[Simple moving average (window n): MA_t = (1/n) * sum_{i=0}^{n-1} x_{t-i}\]
  3. \[Exponential smoothing (one-step): S_t = α * x_t + (1 - α) * S_{t-1}\]
    \[where 0 < α ≤ 1\]
  4. \[Frame interval (seconds) for animation given fps: interval = 1000 / fps (milliseconds in FuncAnimation)\]
🗳️19

Best Practices and Chart Selection

💻 COMPUTER SCIENCE / IT

Best Practices and Chart Selection

Key Point: Mean (average): \u03bc = (1/n) \u2211_{i=1}^{n} x_i

Overview: Choosing the right chart and applying good visual-design practices are essential for clear, truthful, and efficient communication of data. A chart should match the question you want to answer (comparison, trend, distribution, relationship, composition) and be designed so viewers can read values quickly and correctly.

How to select a chart:

  • Comparison between categories: use bar charts (vertical or horizontal) or dot plots.
  • Trends over time: use line charts for continuous time series.
  • Distribution of a single variable: use histograms, boxplots, violin plots.
  • Relationship between two numerical variables: use scatter plots; add trend line if needed.
  • Composition (parts of a whole): use stacked bars or 100% stacked bars; use pie charts only for few categories and when precise comparison is not required.
  • Density/heat patterns: use heatmaps, hexbin plots, or contour plots for dense 2D data.

Design best practices:

  • Title and labels: always include a concise title, axis labels (with units) and a legend when needed.
  • Use an appropriate scale: keep a zero baseline for bar charts; use log scale only when data spans orders of magnitude and label it.
  • Color and contrast: use color-blind–friendly palettes, avoid unnecessary gradients, and use color to encode categorical differences or highlight important data.
  • Simplify: remove chartjunk (3D effects, heavy gridlines, redundant decorations). Keep backgrounds and gridlines light.
  • Sort and aggregate: sort categories by value to make comparisons easier; aggregate or bin continuous data sensibly.
  • Annotate: call out important points or annotate peaks, means, or outliers for clarity.
  • Show variability and uncertainty: include error bars, confidence intervals, or shaded error regions where applicable.
  • Maintain aspect ratio for maps or shapes: distortions can mislead interpretation.

Avoiding misleading charts:

  • Don’t truncate the y-axis in bar charts in a way that exaggerates differences.
  • Avoid pie charts with many slices or slices with similar sizes—people have difficulty comparing angles.
  • Don’t use 3D or perspective effects that distort area or volume perception.
  • Be explicit about transformations (log, percent change) and about how missing data are handled.

Statistical & practical considerations:

  • Choose bin width in histograms carefully (Sturges or Freedman–Diaconis rules help); too few or too many bins hides structure.
  • For correlations, complement scatter plots with correlation coefficients (Pearson/Spearman) and consider outliers’ effect.
  • Use small multiples (multiple consistent plots) rather than overlaying many series in one chart when comparing many groups.

Pyplot-specific tips: Use plt.figure and figsize to control size, ax.set_xlabel/ylabel and ax.set_title for labels, ax.grid for light gridlines, plt.tight_layout to avoid label overlap, and subplots for small multiples. Save high-resolution images with plt.savefig(..., dpi=300).

📌 Examples
  • School marks comparison: Use a bar chart to compare average marks of different subjects, sorted descending to highlight the best and worst subjects.
  • Monthly sales trend: Use a line chart to show monthly revenue over a year, add markers and a moving-average line to reveal seasonality.
  • Age distribution of voters: Use a histogram with Freedman–Diaconis bin width to reveal multimodal structure, and a boxplot to show median and outliers.
  • Height vs weight study: Use a scatter plot with a regression line and Pearson correlation coefficient to show the relationship between height and weight.
  • Market share of smartphone brands: If only 3–5 brands, a pie chart or a 100% stacked bar can show composition; otherwise use a horizontal bar chart for clarity.
🧮 Formulas
  1. \[Mean (average): \u03bc = (1/n) \u2211_{i=1}^{n} x_i\]
  2. \[Sample standard deviation: s = sqrt( (1/(n-1)) \u2211_{i=1}^{n} (x_i - \u03bc)^2 )\]
  3. \[Pearson correlation coefficient: r = Cov(X,Y) / (s_X s_Y)\]
    \[where Cov(X,Y) = (1/(n-1)) \u2211 (x_i-\u03bc_X)(y_i-\u03bc_Y)\]
  4. \[Linear regression line: y = m x + c\]
    \[with slope m = Cov(X,Y)/Var(X) and c = \u03bc_Y - m \u03bc_X\]
  5. \[Sturges' rule for histogram bins: k = 1 + log2(n)\]
  6. \[Freedman–Diaconis bin width: h = 2 * IQR(X) / n^(1/3) (useful for histogram binning)\]
💻20

Common Pitfalls and Troubleshooting

💻 COMPUTER SCIENCE / IT

Common Pitfalls and Troubleshooting

Key Point: Min-max normalization (scale to [0,1]): x_normalized = (x - x_min) / (x_max - x_min)

Data-visualisation with Matplotlib's Pyplot is powerful but beginners often hit recurring pitfalls that produce misleading, ugly, or wrong charts. This section lists the common problems, explains why they occur, and gives troubleshooting steps and best practices.

  • Choosing the wrong chart type: Using a line plot for categorical comparison or a pie for many categories can obscure meaning. Match chart type to the data and question (time-series → line, distribution → histogram/boxplot, relationship → scatter).
  • Poor labeling and axes: Missing or ambiguous axis labels, units, or titles make plots uninterpretable. Always set a clear title, x/y labels, and a legend when there are multiple series. Format tick labels (rotate, reduce frequency) to avoid overlap.
  • Scale and transform mistakes: Using linear scale when data spans many orders of magnitude can hide structure; using log scale with zeros/negatives causes NaNs or runtime errors. Check your data before applying transforms.
  • Overplotting and visual clutter: Plotting thousands of points with opaque markers or many overlapping lines hides patterns. Use alpha transparency, subsampling, point-size adjustments, or density plots/hexbin to reveal structure.
  • Missing or invalid data: NaNs, infinities, or string values in numeric arrays silently break plots or produce gaps. Inspect and clean data (drop/replace NaNs, convert types) before plotting.
  • Wrong data ordering: For time-series and connected line plots, unordered x-values produce jagged or incorrect lines. Sort by x (date/time or independent variable) before plotting.
  • Stateful vs object-oriented API confusion: Relying only on plt (stateful) can cause figure/axes mix-ups in complex code, subplots, or functions. Prefer fig, ax = plt.subplots() and call ax.plot(...), ax.set_title(...), etc., to avoid accidental cross-talk.
  • Figure sizing, DPI and resolution issues: Small default figure size or low DPI makes figures unreadable or produces poor-quality saved images. Set figsize and dpi appropriately and remember pixels = inches * dpi.
  • Saving and showing order: Calling plt.show() in some environments clears interactive state; if you get an empty saved image, call plt.savefig(...) before plt.show(), or explicitly manage figures with plt.close().
  • Legend and annotation placement: Legends covering data hide information. Use best location options (e.g., loc='best'), bbox_to_anchor, or place legends outside the axes. Use annotations sparingly and with clear arrows/offsets.
  • Color and accessibility: Poor color choices (too-similar hues, red/green-only palettes) make plots hard to read or inaccessible to color-blind viewers. Use colorblind-friendly palettes and mark different series with both color and marker/linestyle differences.
  • Performance with large data: Plotting millions of points with default markers is slow and memory heavy. Use rasterized plots, downsampling, aggregation, or specialized libraries (Datashader) for very large datasets.
  • Incorrect axis aspect or inverted axes: Forgetting to set aspect ratio can distort perception (important for spatial plots). Use ax.set_aspect('equal') when required.

Troubleshooting checklist (quick):

  • Inspect raw data: print(head), shapes, dtypes, min/max, null counts.
  • Sort data (if needed) and convert types explicitly (dates → pd.to_datetime, category → codes).
  • Use ax = plt.subplots() to avoid state issues; call ax methods directly.
  • Handle NaNs/infs before plotting: mask or fill as appropriate.
  • Adjust figure size, dpi, tick frequency, and rotate x-ticks for readability.
  • Try smaller subsets or aggregated views to debug visual issues, then scale up.

Following these practices produces clearer, correct, and reproducible visualisations with Pyplot.

📌 Examples
  • Monthly sales time-series where x-axis labels overlap. Problem: default tick frequency and long month names. Fix: rotate xtick labels (plt.xticks(rotation=45)), reduce tick count with ax.set_xticks(...), or format dates with matplotlib.dates.DateFormatter.
  • Attempting log scale on data containing zero/negative values. Problem: ax.set_xscale('log') produces warnings or empty segments because log(0) is undefined. Fix: filter out <=0 values or add a small offset (careful: offsets change interpretation) or use symlog which handles small values.
  • Plotting categorical strings directly and getting unexpected results. Problem: passing a list of strings as x with multiple series may plot incorrectly or unsorted. Fix: convert categories to pandas.Categorical (ordered) or map to integer codes; or use seaborn which handles categorical axes.
  • Multiple plots in a loop producing overlapping lines and growing memory use. Problem: not clearing or closing figures; previous plots remain in memory. Fix: call plt.clf(), plt.close(fig) at end of loop or use fig, ax = plt.subplots() inside loop and close when done.
  • Saving an apparently blank figure. Problem: using interactive backends and calling plt.show() before plt.savefig() or not creating a figure object. Fix: call plt.savefig('name.png', bbox_inches='tight') before plt.show(), or explicitly save fig: fig.savefig(...).
🧮 Formulas
  1. \[Min-max normalization (scale to [0,1]): x_normalized = (x - x_min) / (x_max - x_min)\]
  2. \[Z-score standardization: z = (x - μ) / σ\]
    \[where μ is mean and σ is standard deviation\]
  3. \[Log transform (base e or 10): x' = log(x)\]
    \[only valid for x > 0\]
  4. \[Moving average (window w): MA_t = (1/w) * sum_{i=0}^{w-1} x_{t-i}\]
  5. \[Pixel dimensions for output image: pixels = inches * dpi (per axis)\]
    \[Example: width_px = figsize_inches_width * dpi\]

Key Concepts

Matplotlib
A comprehensive Python library for creating static, interactive, and animated visualizations.
pyplot
A Matplotlib module (commonly imported as plt) that provides a MATLAB-like plotting interface.
Figure
The top-level container in Matplotlib that holds one or more Axes (plots) and other artists.
Axes
An area on the Figure where data is plotted (includes x/y axis, ticks, labels, and plots).
plot()
Function to draw 2D line plots connecting data points (default for line charts).
scatter()
Function to create scatter (dot) plots showing the relationship between two variables.
bar()
Function to draw vertical bar charts for categorical comparisons.
hist()
Function to create histograms that show frequency distributions of numerical data.
pie()
Function to create pie charts that display proportions of a whole.
subplots()
Convenience function to create a Figure and an array of Axes for multiple plots in one figure.
xlabel / ylabel
Functions to set labels for the x-axis and y-axis respectively.
title()
Function to add a title to the current Axes (top of the plot).
legend()
Displays a legend that explains plotted lines or markers when labels are provided.
grid()
Turns on/off or customizes grid lines to improve readability of the plot.
marker
Style of the point marker used in plots (e.g., 'o' circle, 's' square, '^' triangle).
linestyle
Style of the connecting line (e.g., '-', '--', '-.', ':') in line plots.
colormap (cmap)
A mapping of scalar data to colors used especially in scatter, imshow, and contour plots.
alpha
Parameter controlling transparency of plot elements; 0 is fully transparent, 1 is opaque.
xlim / ylim
Functions to set the visible range (limits) of the x-axis and y-axis.
savefig()
Saves the current Figure to a file (PNG, PDF, SVG, etc.) with optional DPI and bounding box.

Practice Questions

  1. What is the standard import statement for pyplot and what does the alias serve? / pyplot के लिए मानक import कथन क्या है और उपनाम किस काम आता है?
    Show answer

    import matplotlib.pyplot as plt; the alias plt keeps code short and is the universal convention for calling pyplot functions. / import matplotlib.pyplot as plt; उपनाम plt कोड को संक्षिप्त रखता है और pyplot फलनों को बुलाने की सार्वभौमिक परंपरा है।

  2. Differentiate between a Figure and an Axes object in Matplotlib. / Matplotlib में Figure और Axes ऑब्जेक्ट में अंतर कीजिए।
    Show answer

    A Figure is the entire canvas/window and may contain multiple Axes; an Axes is a single plot area holding data, x/y axes, ticks, labels and title. / Figure पूरा कैनवास/विंडो है जिसमें कई Axes हो सकते हैं; Axes एक अकेला प्लॉट क्षेत्र है जिसमें डेटा, x/y अक्ष, टिक, लेबल व शीर्षक होते हैं।

  3. Which chart type best shows the distribution of a single continuous variable, and which shows the relationship between two variables? / किस प्रकार का चार्ट एक सतत चर का वितरण सर्वोत्तम दर्शाता है, और कौन सा दो चरों के बीच संबंध?
    Show answer

    A histogram best shows the distribution of one continuous variable; a scatter plot shows the relationship/correlation between two numeric variables. / हिस्टोग्राम एक सतत चर का वितरण सर्वोत्तम दर्शाता है; स्कैटर प्लॉट दो संख्यात्मक चरों के बीच संबंध/सहसंबंध दर्शाता है।

  4. Write pyplot code to create a labelled line plot of days vs temperature with markers and grid. / दिन बनाम तापमान का मार्कर व ग्रिड सहित लेबल किया गया रेखा प्लॉट बनाने का pyplot कोड लिखिए।
    Show answer

    plt.plot(days, temps, marker='o', linestyle='-'); plt.xlabel('Day'); plt.ylabel('Temp'); plt.title('Daily Temperature'); plt.grid(True); plt.show() / plt.plot(days, temps, marker='o', linestyle='-'); plt.xlabel('Day'); plt.ylabel('Temp'); plt.title('Daily Temperature'); plt.grid(True); plt.show()

  5. If a figure has figsize=(8,5) and dpi=100, what are its pixel dimensions? / यदि किसी figure का figsize=(8,5) और dpi=100 है, तो उसकी पिक्सेल विमाएँ क्या होंगी?
    Show answer

    Pixels = inches × dpi, so width = 8×100 = 800 px and height = 5×100 = 500 px. / पिक्सेल = इंच × dpi, अतः चौड़ाई = 8×100 = 800 px और ऊँचाई = 5×100 = 500 px।

  6. How do you create a 2x2 grid of subplots and how many total plots does it hold? / 2x2 सबप्लॉट ग्रिड कैसे बनाते हैं और इसमें कुल कितने प्लॉट होते हैं?
    Show answer

    fig, axes = plt.subplots(2, 2) creates the grid; total plots = nrows × ncols = 2×2 = 4. / fig, axes = plt.subplots(2, 2) ग्रिड बनाता है; कुल प्लॉट = nrows × ncols = 2×2 = 4।

  7. Why must plt.axis('equal') be used with a pie chart, and when should pie charts be avoided? / पाई चार्ट के साथ plt.axis('equal') क्यों आवश्यक है, और पाई चार्ट कब टालने चाहिए?
    Show answer

    plt.axis('equal') keeps the pie circular rather than elliptical; pie charts should be avoided when there are many categories (more than about 7). / plt.axis('equal') पाई को दीर्घवृत्ताकार के बजाय वृत्ताकार रखता है; जब श्रेणियाँ बहुत हों (लगभग 7 से अधिक) तब पाई चार्ट टालने चाहिए।

  8. Write code to save a high-quality plot to a file without clipping labels. / लेबल कटे बिना उच्च गुणवत्ता वाला प्लॉट फ़ाइल में सहेजने का कोड लिखिए।
    Show answer

    plt.savefig('plot.png', dpi=300, bbox_inches='tight'); use tight_layout() before saving to prevent label clipping. / plt.savefig('plot.png', dpi=300, bbox_inches='tight'); लेबल कटने से बचाने हेतु सहेजने से पहले tight_layout() का प्रयोग करें।

Related Laws & Principles

Explore all

Foundational laws & principles connected to this chapter — tap to open in the Laws Explorer.

Loading related laws…
Sourced from 261 content files · LLOS Learn · browse all chapters