Data Visualization with Matplotlib Pyplot
Data visualization is the graphical representation of information and data. In CBSE Class 12 Information Practices (Code 065), Matplotlib (specifically the matplotlib.pyplot module) is the standard charting library used to generate line charts, bar plots, and histograms.
1. Introduction to matplotlib.pyplot
matplotlib.pyplot is a collection of command style functions that make Matplotlib work like MATLAB. Each pyplot function makes some change to a figure (e.g., creates a figure, creates a plotting area in a figure, plots lines or bars, decorates the plot with labels).
python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pdEssential Anatomy of a Pyplot Chart
- Figure: The whole window or page on which everything is drawn.
- Axes: The region of the figure containing the data space (
-axis and -axis). - Title (
plt.title()/plt.suptitle()): Text heading for the chart. - Labels (
plt.xlabel(),plt.ylabel()): Descriptive labels for the coordinate axes. - Legend (
plt.legend()): A guide explaining the colors or markers corresponding to datasets. - Grid (
plt.grid()): Background reference lines. - Show (
plt.show()): Displays the chart on screen. - Save (
plt.savefig()): Exports the figure to an image file (e.g.,png,pdf,jpg).
2. Line Plots (plt.plot())
A line plot connects a series of data points with straight line segments. It is ideal for showing continuous data trends over time.
Syntax
python
plt.plot(x, y, color='...', linestyle='...', linewidth=..., marker='...', markersize=..., label='...')Parameters Deep Dive
| Parameter | Description | Accepted Values |
|---|---|---|
color or c | Line and marker color | 'r', 'g', 'b', 'c', 'm', 'y', 'k', 'w', '#FF5733', 'purple' |
linestyle or ls | Style of the line | '-' (solid), '--' (dashed), '-.' (dash-dot), ':' (dotted) |
linewidth or lw | Thickness of the stroke | Numeric integer or float (e.g., 2, 2.5, 4) |
marker | Data point indicator shape | 'o' (circle), 's' (square), '^' (triangle), '*' (star), '+' (plus), 'D' (diamond) |
markersize or ms | Size of the marker symbol | Numeric (e.g., 6, 8, 10) |
markeredgecolor (mec) | Color of marker border | Color string |
markerfacecolor (mfc) | Color of marker fill | Color string |
label | Name of series for legend | String |
Complete Line Plot Example
python
import matplotlib.pyplot as plt
# Monthly Sales Data (in Lakhs)
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
sales_2025 = [12, 18, 15, 24, 28, 35]
sales_2026 = [15, 22, 20, 31, 36, 42]
plt.figure(figsize=(8, 4.5))
plt.plot(months, sales_2025, color='royalblue', linestyle='--', marker='o', linewidth=2, label='FY 2024-25')
plt.plot(months, sales_2026, color='crimson', linestyle='-', marker='s', linewidth=2.5, label='FY 2025-26')
plt.title('Monthly Sales Growth Comparison', fontsize=14, fontweight='bold', color='navy')
plt.xlabel('Financial Month', fontsize=11)
plt.ylabel('Revenue (₹ in Lakhs)', fontsize=11)
plt.grid(True, linestyle=':', alpha=0.6)
plt.legend(loc='upper left')
plt.show()3. Bar Charts (plt.bar() & plt.barh())
Bar charts represent categorical data with rectangular bars where heights or lengths are proportional to the values they represent.
Vertical Bar Chart (plt.bar())
python
plt.bar(x, height, width=0.8, color='...', edgecolor='...', label='...')python
import matplotlib.pyplot as plt
streams = ['Science', 'Commerce', 'Humanities', 'Vocational']
students = [450, 620, 380, 150]
colors = ['teal', 'orange', 'forestgreen', 'mediumpurple']
plt.bar(streams, students, width=0.5, color=colors, edgecolor='black', linewidth=1.2)
plt.title('Senior Secondary Stream Enrollment (2026)', fontsize=13)
plt.xlabel('Academic Stream')
plt.ylabel('Number of Enrolled Students')
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()Multiple Bar Charts (Side-by-Side Comparison)
IMPORTANT
High-Yield CBSE Question: Creating multiple bar charts on the same width.
Let
- Array of
-coordinates: - Series 1 position:
or - Series 2 position:
or
python
import matplotlib.pyplot as plt
import numpy as np
terms = ['Term 1', 'Term 2', 'Pre-Board']
section_A = [78, 85, 92]
section_B = [72, 88, 89]
x = np.arange(len(terms)) # [0, 1, 2]
width = 0.35
plt.bar(x - width/2, section_A, width=width, label='Section A', color='#1E88E5')
plt.bar(x + width/2, section_B, width=width, label='Section B', color='#FFC107')
plt.xticks(x, terms) # Replaces [0, 1, 2] with ['Term 1', 'Term 2', 'Pre-Board']
plt.title('Average Subject Score by Section')
plt.xlabel('Examination')
plt.ylabel('Average Score (%)')
plt.ylim(0, 100)
plt.legend()
plt.show()Horizontal Bar Chart (plt.barh())
python
plt.barh(y, width, height=0.8, color='...', edgecolor='...')4. Histograms (plt.hist())
A histogram represents the frequency distribution of continuous numerical data. The continuous data range is divided into a series of intervals called bins.
Syntax
python
plt.hist(x, bins=10, range=None, density=False, cumulative=False, color='...', edgecolor='...', orientation='vertical')Key Parameters
bins: Specifies the number of equal-width bins (e.g.,bins=5) OR a sequence of bin edges (e.g.,bins=[0, 20, 40, 60, 80, 100]).edgecolor: Highly recommended (edgecolor='black') to make bin boundaries distinctly visible.cumulative: IfTrue, computes a cumulative frequency histogram (ogive).
Example: Score Frequency Distribution
python
import matplotlib.pyplot as plt
marks = [45, 55, 62, 71, 73, 75, 78, 82, 84, 85, 88, 90, 92, 95, 98, 58, 67, 74, 86, 91]
custom_bins = [40, 50, 60, 70, 80, 90, 100]
plt.hist(marks, bins=custom_bins, color='lightseagreen', edgecolor='black', linewidth=1.2)
plt.title('Score Distribution in Class 12 IP Pre-Board')
plt.xlabel('Marks Range (Bins)')
plt.ylabel('Number of Students (Frequency)')
plt.xticks(custom_bins)
plt.grid(axis='y', linestyle=':')
plt.show()5. Saving Figures (plt.savefig())
To save the plot to local storage rather than or in addition to displaying it:
python
plt.savefig('output_chart.png', dpi=300, bbox_inches='tight')WARNING
Always call plt.savefig() BEFORE calling plt.show(). If you call plt.show() first, Matplotlib initializes a new blank canvas, and savefig() will export an empty white image!
6. CBSE Exam Traps & Common Errors
| Exam Trap | Incorrect Code | Correct Code | Explanation |
|---|---|---|---|
Missing plt.show() | plt.plot(x, y) (script ends) | plt.plot(x, y)plt.show() | Without plt.show(), the window never renders in desktop Python environments. |
savefig() after show() | plt.show()plt.savefig('f.png') | plt.savefig('f.png')plt.show() | plt.show() closes and resets the current active figure canvas. |
plt.legend() without label | plt.plot(x, y)plt.legend() | plt.plot(x, y, label='Data')plt.legend() | If no label is defined in plot functions, plt.legend() shows an empty box or error. |
| Unequal coordinate lengths | x = [1, 2, 3]y = [10, 20]plt.plot(x, y) | x = [1, 2, 3]y = [10, 20, 30]plt.plot(x, y) | Raises ValueError: x and y must have same first dimension. |
7. Board Practice Drills
Drill 1: Code Writing (3 Marks)
Write a Python code snippet to draw a horizontal bar chart of 5 programming languages with their popularity scores ('coral', title to 'Language Popularity', and add appropriate axis labels.
python
import matplotlib.pyplot as plt
languages = ['C++', 'Python', 'Java', 'Ruby', 'JavaScript']
popularity = [85, 92, 78, 65, 95]
plt.barh(languages, popularity, color='coral', edgecolor='black')
plt.title('Language Popularity')
plt.xlabel('Popularity Index')
plt.ylabel('Programming Language')
plt.show()Drill 2: Output Identification (2 Marks)
Given the following code:
python
import matplotlib.pyplot as plt
import numpy as np
data = [12, 15, 18, 22, 25, 28, 32, 35, 40]
plt.hist(data, bins=[10, 20, 30, 40, 50], edgecolor='black')
plt.show()Question: What are the frequencies for the bin intervals [10, 20), [20, 30), and [30, 40]?
Answer:
- Bin
[10, 20)containsFrequency = 3 - Bin
[20, 30)containsFrequency = 3 - Bin
[30, 40]containsFrequency = 3 - Bin
(40, 50]containsFrequency = 0