XII_Chapter_III_IP_Sumita_Arora_Comprehensive Guide to Data Visualization with Python Matplotlib Pyplot
Learn to create and customize line, bar, and histogram charts using Python's Matplotlib Pyplot. Understand visualization basics, installation, key methods, and real-world applications for effective data presentation.
XII_Chapter_III_IP_Sumita_Arora_Comprehensive Guide to Data Visualization with Python Matplotlib Pyplot
1.
CHAPTER: 3
Plotting withPyplot
Data Visualization using Python • Matplotlib • Pyplot
Python 3 Matplotlib Hands-on Coding
2.
C H AP T E R R O A D MA P
Learning Outcomes
By the end of this chapter, you will be able to...
EXPLAIN
why data visualization matters and
where it is used in real life
INSTALL & IMPORT
the Matplotlib library and use the
Pyplot module correctly
CREATE
line charts, bar charts and horizontal
bar charts using Python code
CUSTOMIZE
colours, markers, line width and chart
size for clear presentation
COMPARE
different chart types and choose the
right one for given data
APPLY
plotting skills to solve real classroom
and board-exam style problems
3.
R E AL - W O R L D R E L E V A N C E
Why Should We Learn This Chapter?
"A picture is worth a thousand numbers." Every industry today uses charts to make sense of data.
Artificial Intelligence
Visualizing model accuracy & training
trends
Business
Sales dashboards & quarterly
performance charts
Healthcare
Patient vitals, disease spread &
recovery graphs
Sports Analytics
Player performance & match statistics
Weather Forecast
Temperature, rainfall & climate trend
charts
Finance
Stock price movement & investment
growth charts
4.
C H AP T E R O V E R V I E W
Your Journey Through Pyplot
1
Visualization
Basics
2
Pyplot Setup
& Methods
3
Line
Chart
4
Bar
Chart
5
Multiple &
Horizontal Bars
6
Histogram
7
Customizing
the Plot
We will build each chart type step-by-step: syntax → code → output → customization → practice.
5.
T O PI C 1
What is Data Visualization?
DEFINITION
Data Visualization is the graphical representation of information and data
using visual elements like charts, graphs, and maps.
"See the story
behind the numbers"
Classroom Example: Instead of reading 40 students'
marks in a list, a bar chart instantly shows who scored
highest!
▸ Turns raw numbers into pictures our brain understands instantly
▸ Helps us spot patterns, trends and comparisons quickly
▸ Makes reports and presentations easier to understand
▸ A single chart can replace pages of numeric tables
Features:
6.
T O PI C 2 . 3
Types of Charts in Matplotlib
Different data needs different charts — here is a quick preview of what we will learn.
Line Chart
A graphical representation that
connects data points with lines to
show trends or changes over time.
plot()
Bar Chart
Uses rectangular bars to compare
quantities across different categories.
bar()
Histogram
Displays the frequency distribution of
continuous data using adjacent bars.
hist()
Scatter Plot
Shows the relationship between two
variables using dots on a coordinate
plane.
scatter()
Pie Chart
Represents data as slices of a circle,
illustrating parts of a whole.
pie()
Box Plot
Summarizes data distribution through
quartiles, highlighting median and
outliers.
boxplot()
7.
T O PI C 2 . 1
Installing & Importing Matplotlib
STEP 1 — Install (one time only, in command prompt / terminal)
pip install matplotlib
STEP 2 — Import Pyplot in your Python program
import matplotlib.pyplot as plt
# "plt" is the standard short name used by all programmers
REMEMBER
We import Pyplot as "plt" — this short name (alias) is a worldwide convention.
Always use it so your code matches textbooks and online examples.
WHY "plt" AND NOT SOMETHING ELSE?
▸ Shorter to type again and again
▸ Every teacher, book and website uses "plt"
▸ You could technically use any name, but it
breaks the convention
▸ CBSE exams expect standard aliasing
matplotlib is Python's most popular
plotting library!
8.
T O PI C 2 . 2
Working with Pyplot Methods
Pyplot gives ready-made functions (methods) to build and display a chart. Here are the ones you will use the most:
METHOD WHAT IT DOES
plt.plot() Draws a line chart
plt.bar() / plt.barh() Draws a vertical / horizontal bar chart
plt.hist() Draws a histogram
plt.title() Adds a chart title
plt.xlabel() / plt.ylabel() Labels the X-axis and Y-axis
plt.legend() Shows a legend box for multiple data series
plt.grid() Adds gridlines for easier reading
plt.show() Displays the final chart on screen
plt.savefig() Saves the chart as an image file
9.
QUICK CHECK 1
MCQs
1.Which alias is conventionally used for matplotlib.pyplot?
(a) mp (b) plt (c) pyp (d) mplt
Answer: (b) plt
2. Which function actually displays the chart on screen?
(a) plt.draw() (b) plt.view() (c) plt.show() (d) plt.display()
Answer: (c) plt.show()
SHORT QUESTION
Name any two real-life fields where data visualization is used,
with one example each.
THINK & ANSWER
Why do you think a chart communicates faster than a table of the
same numbers?
Answer:
• Healthcare: Representing data such as age distribution of
cases or vaccination progress.
• Sports: Tracking passes, shots, and other key actions in games.
Answer:
The reason a chart communicates faster than a table of the same
numbers is due to the visual nature of charts.
10.
T O PI C 3
Line Chart — plot() Documentation
A Matplotlib line chart links data points with lines to show trends over a sequence like time. It’s great for visualizing
how values change and for comparing data points clearly.
matplotlib.pyplot.plot(x, y, color=None, linestyle='-', linewidth=1, marker=None, label=None)
Parameters:
• x: Values to be displayed on the x-axis.
• y: Values to be displayed on the y-axis.
• color: Specifies the color of the line (for example, 'red', 'blue', 'green').
• linestyle: Defines the style of the line, such as solid ('-'), dashed ('--'), dotted (':'), or dash-dot ('-.').
• linewidth: Sets the thickness of the line.
• marker: Displays a marker at each data point (such as 'o', 's', '^', '*').
• label: Specifies a label for the plotted line, which is displayed when using legend().
Syntax:
11.
T O PI C 3
Creating a Line Chart — plot()
PROBLEM: Plot the temperature recorded on 5 days of a week: 30, 32, 29, 35, 33 °C
import matplotlib.pyplot as plt
days = [1, 2, 3, 4, 5]
temp = [30, 32, 29, 35, 33]
plt.plot(days, temp) # draws the line
plt.show() # displays the chart
OUTPUT
IMPORTANT NOTE
plot(x, y) needs two lists of equal length: one for the
X-axis, one for the Y-axis.
SAMPLE PROGRAM:
12.
T O PI C 3
Line Chart — Plot Size & Grid
SPECIFYING PLOT SIZE
import matplotlib.pyplot as plt
days = [1, 2, 3, 4, 5]
temp = [30, 32, 29, 35, 33]
plt.figure(figsize=(8, 5))
plt.plot(days, temp)
plt.show()
REMEMBER
figsize=(width, height) is measured in inches. Use it BEFORE
plot().
ADDING GRID
EXAM TIP
grid(True) adds light background lines — makes it easy to read
exact values. A favourite one-mark question!
import matplotlib.pyplot as plt
days = [1, 2, 3, 4, 5]
temp = [30, 32, 29, 35, 33]
plt.figure(figsize=(8, 5))
plt.plot(days, temp)
plt.grid(True)
plt.show()
OUTPUT
SAMPLE PROGRAM:
OUTPUT
SAMPLE PROGRAM:
13.
T O PI C 3
Line Chart — Colour & Width
PARAMETER
color
linewidth
A number — bigger number = thicker line
COMMON MISTAKE
Writing colour = "Green" (capital letter) or a spelling mistake gives
an error. Colour names are case-sensitive lowercase strings.
import matplotlib.pyplot as plt
days = [1, 2, 3, 4, 5]
temp = [30, 32, 29, 35, 33]
plt.figure(figsize=(8, 5))
plt.plot(days, temp, color = 'green',linewidth = 3)
plt.show()
SAMPLE PROGRAM:
OUTPUT
Letter Alias Color Name Hex Color
Code
‘b’ ‘blue’ ‘#0000ff’
‘g’ ‘green’ ‘#008000’
‘r’ ‘red’ ‘#ff0000’
‘c’ ‘cyan’ ‘#00bfbf’
‘m' ‘magenta’ ‘#bf00bf’
‘y' ‘yellow’ ‘#bfbf00’
‘k' ‘black’ ‘#000000’
‘w' ‘white’ ‘#ffffff’
14.
T O PI C 3
Line Chart — Adding Markers
A marker highlights each data point on the line with a small shape.
SOME COMMON MARKER TYPES
'o' → circle
'*' → star
's' → square
'D' → diamond
REMEMBER
markersize controls how big the marker dot appears.
markerfacecolor can differ from the line colour for extra
emphasis.
import matplotlib.pyplot as plt
days = [1, 2, 3, 4, 5]
temp = [30, 32, 29, 35, 33]
plt.figure(figsize=(8, 5))
plt.plot(days, temp,marker = 'o',markersize = 10,markerfacecolor = 'red')
plt.show()
OUTPUT
SAMPLE PROGRAM:
15.
T O PI C 3 — W R A P U P
Line Chart: Summary & Key Takeaways
KEY TAKEAWAYS
▸ plt.plot(x, y) draws a line chart connecting data points
▸ figsize=(w, h) controls chart size in inches
▸ grid(True) adds gridlines for readability
▸ color and linewidth style the line itself
▸ marker, markersize, markerfacecolor style the data points
▸ Always end with plt.show() to display the chart
COMMON MISTAKE
Common Errors:
• forgetting plt.show()
• mismatched list lengths for x and y
• using capital letters in colour/marker names.
EXAM TIP
Board exams often ask you to write a program AND
identify one error in a given line-chart code. Practise
both!
DID YOU KNOW?
The very first known line chart was created by
William Playfair in 1786 to show England's trade
data!
16.
QUICK CHECK 2
MCQs
1.Which parameter controls the thickness of a line in plot()?
(a) linesize (b) linewidth (c) thickness (d) width
Answer: (b) linewidth
2. Which parameter is used to colour the marker only (not the line)?
(a) color (b) markercolor (c) markerfacecolor (d) fillcolor
Answer: (c) markerfacecolor
SHORT QUESTION
import matplotlib.pyplot as plt
# Sample data - replace with your lists
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 5, 3]
# Plot x vs y with red dashed line, width 2
plt.plot(x, y, color='red', linestyle='--',
linewidth=2)
# Optional: add labels and title
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('Plot of x vs y')
# Show the plot
plt.grid(True)
plt.show()
THINK & ANSWER
If you wanted to compare two students' monthly attendance on
the same chart, how would a line chart help?
Write one line of code
to plot list "x" against
list "y" with a red
dashed line of width 2. See Trends: You can instantly see if attendance is going up, down, or
staying flat for each student across 12 months.
Direct Comparison: Plot both students on the same chart with 2 different
colored lines. You can see who had higher attendance in which month.
Spot Patterns: Easy to spot things like "Student A drops in exam months"
or "Student B is more consistent".
17.
T O PI C 4
Bar Chart — bar() Documentation
A bar plot compares categories with rectangular bars. Each bar’s height reflects its value, making differences between
categories easy to spot.
matplotlib.pyplot.bar(x, height, width=0.8, color=None, label=None, align='center')
Parameters:
• x: Specifies the positions or category labels for the bars on the x-axis.
• height: Specifies the height (value) of each bar.
• width: Sets the width of the bars. The default value is 0.8.
• color: Specifies the color of the bars. It can be a single color or a list of colors.
• label: Adds a label for the bar plot, which can be displayed using legend().
• align: Specifies how the bars are aligned with the x positions. Common values are 'center'
(default) and 'edge'.
Syntax:
18.
T O PI C 4
Creating a Bar Chart — bar()
PROBLEM: Compare the number of books read by 4 students: Aman-5, Bina-8, Chirag-3, Diya-7
import matplotlib.pyplot as plt
names = ['Aman', 'Bina', 'Chirag', 'Diya']
books = [5, 8, 3, 7]
plt.bar(names, books) # draws vertical bars
plt.show()
IMPORTANT NOTE
bar(x, height) is best for comparing categories — here,
students — side by side.
OUTPUT
SAMPLE PROGRAM:
19.
T O PI C 4
Bar Chart — Changing Bar Width
SAME (COMMON) WIDTH FOR ALL BARS DIFFERENT WIDTH FOR EACH BAR
REMEMBER
width takes a single number (all bars same width) OR a list
matching the number of bars (each bar can differ).
EXAM TIP
Default bar width is 0.8. Values above 1.0 may cause bars to
overlap — good trick question in exams!
OUTPUT
import matplotlib.pyplot as plt
names = ['Aman', 'Bina', 'Chirag', 'Diya']
books = [5, 8, 3, 7]
plt.bar(names, books, width = 0.4)
plt.show()
SAMPLE PROGRAM:
import matplotlib.pyplot as plt
names = ['Aman', 'Bina', 'Chirag', 'Diya']
books = [5, 8, 3, 7]
plt.bar(names, books, width = [0.2, 0.4, 0.6, 0.8])
plt.show()
SAMPLE PROGRAM:
OUTPUT
20.
T O PI C 4
Bar Chart — Changing Bar Colour
SAME (COMMON) COLOUR DIFFERENT COLOUR FOR EACH BAR
ACTIVITY TIME
Try it yourself: change the colour list so that the bar with the
HIGHEST value is always gold, and the rest stay grey.
COMMON MISTAKE
The colour list must have the SAME number of items as the bars —
one colour per category, no more, no less.
import matplotlib.pyplot as plt
names = ['Aman', 'Bina', 'Chirag', 'Diya']
books = [5, 8, 3, 7]
plt.bar(names, books, color = 'teal')
plt.show()
SAMPLE PROGRAM:
OUTPUT
import matplotlib.pyplot as plt
names = ['Aman', 'Bina', 'Chirag', 'Diya']
books = [5, 8, 3, 7]
plt.bar(names, books, color = ['red','green','blue','orange'])
plt.show()
SAMPLE PROGRAM:
OUTPUT
21.
T O PI C 4 — W R A P U P
Bar Chart: Summary & Key Takeaways
KEY TAKEAWAYS
▸ plt.bar(x, height) draws vertical bars for category comparison
▸ width sets bar thickness — one value or a list
▸ color sets bar fill — one value or a list matching bar count
▸ Bar charts are best when comparing DISCRETE categories
▸ Line charts are best when showing CONTINUOUS trends over time
COMMON MISTAKE
Common Errors: list length mismatch between
categories and values; forgetting quotes around
colour names; confusing bar() with barh().
EXAM TIP
Remember: bar chart bars have gaps between them
(discrete categories); histogram bars touch each other
(continuous ranges).
DID YOU KNOW?
Bar charts are believed to have first been used by
William Playfair too — in his 1786 book on trade
statistics!
22.
T O PI C 5
Creating Multiple Bar Charts
Sometimes we need to compare MORE THAN ONE data series for the
same categories — e.g. marks of 2 subjects for the same students.
THE TRICK: ADJUST X-AXIS POSITIONS
▸ Use numpy.arange() to get base X positions for categories
▸ Shift the second series slightly using position + bar thickness
▸ Give each series a different bar thickness / colour
▸ Add plt.legend() so viewers know which colour = which subject
IMPORTANT NOTE
This is also called a "grouped" or "clustered" bar chart — bars for each
category sit side-by-side, grouped together.
GROUPED BARS — CONCEPT
■ Subject A ■ Subject B
Each pair of bars represents one student — placed side by side,
not overlapping.
23.
T O PI C 5
Multiple Bar Charts — Python Code
import numpy as np
import matplotlib.pyplot as plt
students = ['Aman','Bina','Chirag']
maths = [78, 88, 65]
science = [82, 74, 91]
pos = np.arange(len(students)) # base positions
w = 0.35 # bar thickness
plt.bar(pos, maths, w, color=‘#065A82', label='Maths')
plt.bar(pos + w, science, w, color=‘#F2A93B', label='Science')
plt.xticks(pos + w/2, students) # centre category labels
plt.legend()
plt.show()
REMEMBER
pos + w shifts the second set of bars
right by exactly one bar-width, so bars
sit neatly beside each other.
EXAM TIP
xticks(pos + w/2, students) centres the
category name UNDER the pair of bars —
a common exam trick.
COMMON MISTAKE
Forgetting label= in bar() means legend()
will show empty entries.
SAMPLE PROGRAM:
OUTPUT:
24.
QUICK CHECK 3
MCQs
1.Which library function gives evenly spaced base positions for grouped bars?
(a) np.range() (b) np.arange() (c) np.position() (d) np.linspace_bar()
Answer: (b) np.arange()
2. What does plt.legend() require to display correct labels?
(a) title= in bar() (b) label= in bar() (c) name= in bar() (d) key= in bar()
Answer: (b) label= in bar()
SHORT QUESTION
What is the purpose of shifting the second bar series by "pos +
w" instead of plotting it at the same position?
THINK & ANSWER
Can you think of a real school scenario where a grouped bar
chart (2 data series) would be more useful than a simple bar
chart?
Answer: pos → first series, pos + w → second series, so the
bars sit next to each other instead of hiding one another.
A real school scenario: comparing boys vs girls performance
in two subjects (e.g., Maths and Science).
A grouped bar chart lets teachers see side-by-side subject
scores for each group, making it easier to spot strengths or gaps
than a simple bar chart showing only one subject.
25.
T O PI C 6
Creating a Horizontal Bar Chart
Use barh() when category names are long, or you simply want bars running left-to-right instead of bottom-to-top.
import matplotlib.pyplot as plt
subjects = ['AI', 'IP', 'Physics', 'Maths']
hours = [3, 5, 4, 6]
plt.barh(subjects, hours, color="1C7293")
plt.xlabel("Study Hours per Week")
plt.show()
EXAM TIP
barh(y, width) — parameters are swapped
compared to bar(x, height). This swap is a favourite
one-mark exam question!
DID YOU
KNOW?
Horizontal bar charts are the preferred choice in
news infographics when category names (like
country names) are long and would overlap if
placed vertically.
SAMPLE PROGRAM:
OUTPUT:
26.
T O PI C 7
Histogram — hist() Documentation
plt.hist() makes histograms. It splits data into bins, counts values in each bin, and plots the results as bars to show the
data distribution.
matplotlib.pyplot.hist(x, bins=None, *, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid',
orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, data=None, **kwargs)
IMPORTANT PARAMETERS:
• x: data to be represented in the histogram.
• bins: Specifies the number of bins or the bin edges for the
histogram.
• range: The lower and upper range of the bins.
• density: If True, the histogram is normalized to form a probability
density.
• histtype: Defines the type of histogram (e.g., 'bar' for a traditional
bar histogram).
• color: Sets the color of the bars.
• label: Label for the histogram, used in legends.
• edgecolor: Colour of the bar border — improves readability
• cumulative: If True, each bar adds the count of all previous bars
• orientation: 'vertical' (default) or 'horizontal'
Syntax:
RETURNS:
• n: array or list of arrays- The values of the histogram bins.
• binsarray- The edges of the bins. Length nbins + 1 (nbins left
edges and right edge of last bin). Always a single array even when
multiple data sets are passed in.
• patches- BarContainer or list of a single Polygon or list of
such objects- Container of individual artists used to create the
histogram or list of such containers if there are multiple input
datasets.
27.
T O PI C 7
Creating a Histogram — hist()
A histogram shows how numeric data is DISTRIBUTED across ranges (called "bins") — unlike a bar chart, bars touch each other.
PROBLEM: Show the distribution of marks of 30 students out of 100
import matplotlib.pyplot as plt
marks = [45, 67, 78, 34, 88, 92, 56, 60, 73, 81]
plt.hist(marks, bins=10) # divides data into 10 ranges
plt.show()
IMPORTANT NOTE
bins decides how many groups the data range is divided into.
OUTPUT:
SAMPLE PROGRAM:
28.
T O PI C 7
Histogram — Effect of Bin Count
The SAME data can look very different depending on how many bins you choose.
20 BINS — BROADER GROUPS
Fewer, wider bars.
Shows the OVERALL shape clearly.
50 BINS — FINER DETAIL
More, narrower bars.
Shows fine DETAIL but can look noisy.
EXAM TIP
Too few bins hide patterns; too many bins create noise. Choosing the right bin count is a key data-visualization skill often tested conceptually.
import matplotlib.pyplot as plt
marks = [45, 67, 78, 34, 88, 92, 56, 60, 73, 81]
plt.hist(marks, bins=20)
plt.show()
import matplotlib.pyplot as plt
marks = [45, 67, 78, 34, 88, 92, 56, 60, 73, 81]
plt.hist(marks, bins=50)
plt.show()
OUTPUT: OUTPUT:
SAMPLE PROGRAM: SAMPLE PROGRAM:
29.
T O PI C 7
Cumulative & Step Histogram
CUMULATIVE HISTOGRAM
Each bar height = total count SO FAR (adds up all previous bins).
Useful to see "how many students scored below X marks".
STEP HISTOGRAM
Draws only the OUTLINE of the bars (no fill) — useful when comparing
multiple histograms on one chart without blocking each other.
REMEMBER
cumulative=True changes WHAT is counted; histtype changes HOW it is drawn. The two can be combined together.
import matplotlib.pyplot as plt
marks = [45, 67, 78, 34, 88, 92, 56, 60, 73, 81]
plt.hist(marks, bins=10, cumulative = True)
plt.show()
SAMPLE PROGRAM:
import matplotlib.pyplot as plt
marks = [45, 67, 78, 34, 88, 92, 56, 60, 73, 81]
plt.hist(marks, bins=10, histtype = 'step')
plt.show()
SAMPLE PROGRAM:
OUTPUT: OUTPUT:
30.
T O PI C 7
Multiple & Stacked Histograms
MULTIPLE HISTOGRAMS (SIDE BY SIDE) STACKED HISTOGRAM
IMPORTANT NOTE
Passing a LIST OF LISTS to hist() plots more than one dataset
together — great for comparing two sections or two years of data.
EXAM TIP
stacked=True places one dataset's bars ON TOP of the other
instead of beside it — the total bar height shows the combined
count.
import matplotlib.pyplot as plt
classA = [34, 45, 67, 78]
classB = [56, 60, 88, 92]
plt.hist([classA, classB], bins=10, label=['A','B'])
plt.legend()
plt.show()
SAMPLE PROGRAM:
OUTPUT:
import matplotlib.pyplot as plt
classA = [45, 67, 78, 34]
classB = [88, 92, 56, 60]
plt.hist([classA,classB],bins=10,stacked=True,label=['A','B'])
plt.legend()
plt.show()
SAMPLE PROGRAM:
OUTPUT:
31.
T O PI C 7
Horizontal Histogram
import matplotlib.pyplot as plt
marks = [45, 67, 78, 34, 88, 92, 56, 60, 73, 81]
plt.hist(marks, bins=10, orientation = 'horizontal')
plt.show()
EXAM TIP
orientation="horizontal" is the histogram
equivalent of using barh() for bar charts.
COMMON MISTAKE
Common Errors: forgetting bins= (Python then uses default 10, which may not suit your data); mismatching histtype spelling; giving
cumulative a string "True" instead of the boolean True.
SAMPLE PROGRAM:
OUTPUT:
32.
T O PI C 7 — W R A P U P
Histogram: Summary & Key Takeaways
KEY TAKEAWAYS
▸ plt.hist(data, bins=n) shows the DISTRIBUTION of numeric data
▸ Bars touch each other — data is CONTINUOUS, not categorical
▸ bins controls how many ranges the data is split into
▸ cumulative=True gives running totals
▸ histtype and orientation change how the histogram looks
▸ A histogram answers "how many values fall in this range?"
DID YOU KNOW?
The term "histogram" was coined by Karl Pearson in
1895 — from the Greek words "histos" (mast/pole)
and "gramma" (drawing).
EXAM TIP
A very common exam question: "Differentiate between
a Bar Chart and a Histogram." Bar chart = categories
with gaps; Histogram = continuous ranges, bars
touch.
ACTIVITY TIME
Collect the heights (in cm) of all students in your class and plot a histogram with 5 bins!
33.
QUICK CHECK 4
MCQs
1.What is the default number of bins used by plt.hist() if not specified?
(a) 5 (b) 10 (c) 20 (d) 100
Answer: (b) 10
2. Which parameter draws only the outline of histogram bars?
(a) outline (b) edgecolor (c) histtype="step" (d) fill=False
Answer: (c) histtype="step"
SHORT QUESTION
State one key difference between a Bar Chart and a Histogram.
THINK & ANSWER
If a teacher wants to see how many students scored between 0-
33%, 34-66%, and 67-100%, which chart — bar or histogram — is
more suitable, and why?
Answer:
A Bar Chart compares categories (like number of students in
each class), while a Histogram shows the frequency
distribution of continuous data (like how many students
scored within certain mark ranges).
In short: Bar Chart → categories, Histogram → data
intervals.
Answer:
A Histogram is more suitable because the teacher is grouping
scores into interval ranges (0–33%, 34–66%, 67–100%), and
histograms are designed to show the frequency distribution
of continuous data across intervals.
So, use a Histogram → to visualize score ranges.
34.
T O PI C 8
Customizing the Plot — Chart Anatomy
Every good chart has these labelled components. Let's learn to add each one.
Chart Title ← plt.title()
■ Series A
← plt.legend()
← plt.grid()
Y
VALUES
plt.ylabel() →
X VALUES
plt.xlabel()
Small marks along each axis = plt.xticks() / plt.yticks()
35.
T O PI C 8
Customizing — Title & Axis Labels
import matplotlib.pyplot as plt
# Sample data
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
scores = [65, 70, 75, 80, 85]
# Create line chart
plt.plot(days, scores, marker='o', color='blue')
# Customizing title and axis labels
plt.title("Student Performance Over a Week") # Chart Title
plt.xlabel("Days of the Week") # X-axis Label
plt.ylabel("Scores (%)") # Y-axis Label
# Show chart
plt.show()
WHY LABEL EVERYTHING?
▸ A chart without a title is confusing
▸ Axis labels tell the viewer WHAT the numbers mean
▸ fontsize= makes the title stand out
EXAM TIP
CBSE marking schemes often give separate marks for title, xlabel and ylabel —
never skip them in a program-based answer!
SAMPLE PROGRAM:
OUTPUT:
36.
T O PI C 8
Customizing — Axis Limits & Ticks
SETTING LIMITS
plt.ylim(0, 100) # Y-axis 0 to 100
plt.xlim(0, 10) # X-axis 0 to 10
Fixes the visible range of an axis — useful to keep multiple charts on
the same scale for fair comparison.
CUSTOM TICKS
plt.xticks([0,1,2,3], ['Q1','Q2','Q3','Q4'])
plt.yticks(range(0, 101, 20))
Replaces plain numbers with meaningful labels, or controls the
spacing between marks on an axis.
REMEMBER
ylim/xlim take a MIN and MAX value. xticks/yticks can take just positions, or positions PLUS custom text labels.
37.
T O PI C 8
Customizing — Axis Limits & Ticks
import matplotlib.pyplot as plt
# Sample data
days = [1, 2, 3, 4, 5]
scores = [65, 70, 75, 80, 85]
# Create line chart
plt.plot(days, scores, marker='o', color='green')
# Customizing axis limits
plt.xlim(0, 6) # X-axis range from 0 to 6
plt.ylim(60, 90) # Y-axis range from 60 to 90
# Customizing ticks
plt.xticks([1, 2, 3, 4, 5], ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']) # Custom labels
plt.yticks([60, 70, 80, 90]) # Specific tick marks
# Title and labels
plt.title("Student Scores Over Days")
plt.xlabel("Days of the Week")
plt.ylabel("Scores (%)")
# Show chart
plt.show()
SAMPLE PROGRAM:
OUTPUT:
38.
T O PI C 8
Customizing — Adding a Legend
COMMON MISTAKE
legend() only shows entries for plots that were given a label= parameter. If you forget label=, the
legend box will appear empty or missing.
Legend
A Legend in a chart is a guide that explains the meaning of different colors, markers, or line styles used, helping the viewer identify which
data series each visual element represents.
SYNTAX:
matplotlib.pyplot.legend(loc=PositionNumber or String)
COMMON loc VALUES
1 'upper right’ 2 ‘upper left’
3 'lower left’ 4 ‘lower right’
39.
T O PI C 8
Customizing — Adding a Legend
import matplotlib.pyplot as plt
# Sample data
days = [1, 2, 3, 4, 5]
maths_scores = [65, 70, 75, 80, 85]
science_scores = [60, 68, 72, 78, 82]
# Plotting two lines
plt.plot(days, maths_scores, marker='o', color='blue', label='Maths')
plt.plot(days, science_scores, marker='s', color='green', label='Science')
# Adding title and axis labels
plt.title("Student Scores Over Days")
plt.xlabel("Days")
plt.ylabel("Scores (%)")
# Displaying legend
plt.legend()
# Show chart
plt.show()
SAMPLE PROGRAM:
OUTPUT:
40.
T O PI C 8
Customizing — Saving the Figure
Instead of just viewing a chart, you can save it permanently as an image file.
plt.savefig(fname, dpi=None, facecolor='w', edgecolor='w',transparent=False, bbox_inches=None,pad_inches=0.1)
• fname → File name or path (e.g., "chart.png", "output.pdf").
• dpi → Resolution in dots per inch (higher = sharper image).
• facecolor → Background color of the figure.
• edgecolor → Border color around the figure.
• transparent → If True, saves with transparent background.
• bbox_inches → Bounding box option ('tight' trims extra whitespace).
• pad_inches → Padding around the figure when using bbox_inches.
COMMON MISTAKE
plt.show() clears the figure from memory after displaying it. Calling savefig() AFTER show() often saves a BLANK image — always savefig() first!
savefig() Syntax and Parameters:
41.
T O PI C 8
Customizing — Saving the Figure
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create a line chart
plt.plot(x, y, marker='o', color='blue', label="y = 2x")
plt.title("Line Chart Example")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
# Save the figure
plt.savefig("C:UsersMYPCDesktopline_chart.png", dpi=300,
bbox_inches='tight', transparent=True)
# Display the chart
plt.show()
SAMPLE PROGRAM:
OUTPUT:
Image file is saved at the given location i.e. Desktop
42.
T O PI C 8 — W R A P U P
Customization: Summary & Key Takeaways
KEY TAKEAWAYS
▸ title(), xlabel(), ylabel() explain what the chart shows
▸ xlim()/ylim() fix the visible axis range
▸ xticks()/yticks() customize axis marks and labels
▸ legend() needs label= set inside each plot/bar call
▸ savefig() must be called BEFORE show()
▸ A well-labelled chart earns full marks in board exams!
EXAM TIP
A full "Chart Customization" program question
typically expects: title, both axis labels, legend (if
multiple series) and grid — check all four before
submitting!
DID YOU KNOW?
Matplotlib's name is a nod to MATLAB, whose
plotting style inspired Pyplot's command syntax.
ACTIVITY TIME
Take your bar chart from Part 1 and add a title, both axis labels, and a legend — then save it as a PNG.
43.
QUICK CHECK 5
MCQs
1.Which function must be called BEFORE plt.show() to correctly save a chart?
(a) plt.export() (b) plt.save() (c) plt.savefig() (d) plt.write()
Answer: (c) plt.savefig()
2. Which function is used to display the legend box on a chart?
(a) plt.key() (b) plt.legend() (c) plt.label() (d) plt.info()
Answer: (b) plt.legend()
SHORT QUESTION
Write the code to set the Y-axis limits of a chart from 0 to 50.
THINK & ANSWER
Why do you think CBSE examiners give separate marks for title,
labels and legend rather than just for the plot() line?
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 45]
# Plot line chart
plt.plot(x, y, marker='o')
# Set Y-axis limits
plt.ylim(0, 50)
plt.show()
CBSE examiners give separate marks for title, labels, and
legend because these elements show whether a student can
make the chart clear, complete, and meaningful for
interpretation.
The plot() line only draws the graph, but title, axis labels,
and legend demonstrate proper presentation and
communication of data, which is a key skill being assessed.
44.
COMPLETE CHAPTER SUMMARY— 2 MINUTE REVISION
1. Visualization
Pictures explain data faster
2. Setup
import matplotlib.pyplot as plt
3. plot()
Line Chart — trends
4. bar()/barh()
Bar Chart — comparison
5. hist()
Histogram — distribution
6. Customize
title, label, legend, grid, save
MEMORY TRICK: "Very Simple Line Bars Have Colours" → Visualize, Setup, Line, Bar, Histogram, Customize
Chart choice reminder: Line = trend over time | Bar = compare categories | Histogram = distribution of continuous data
KEYWORDS
plot • bar • barh • hist • bins • title • xlabel • ylabel • legend • grid • figsize • savefig
45.
R E VI S I O N K I T
Common Mistakes Students Make
Forgetting plt.show() — the chart is built but never
displayed
Mismatched list lengths between x and y data
Using capital letters in colour names, e.g. "Red" instead
of "red"
Calling plt.savefig() AFTER plt.show() — produces a
blank saved image
Forgetting label= in plot()/bar(), so legend() shows empty
entries
Confusing bar() (vertical) with barh() (horizontal)
parameter order
Using a bar chart for continuous numeric data instead
of a histogram
Not resetting figsize before creating a new chart in the
same program
46.
R E VI S I O N K I T
Important Functions — Cheat Sheet
plt.plot(x,y) Line chart
plt.bar(x,h) Vertical bar chart
plt.barh(y,w) Horizontal bar chart
plt.hist(data,bins) Histogram
plt.title(t) Chart title
plt.xlabel(t)/ylabel(t) Axis labels
plt.xlim()/ylim() Axis range
plt.xticks()/yticks() Axis marks
plt.legend() Legend box
plt.grid(True) Gridlines
plt.figure(figsize=(w,h)) Canvas size
plt.savefig(name) Save chart as file
plt.show() Display chart
47.
R E VI S I O N K I T
Syntax — Cheat Sheet
import matplotlib.pyplot as plt
# Line Chart
plt.plot(x, y, color='blue', linewidth=2,
marker='o', markersize=8)
# Bar Chart
plt.bar(x, height, width=0.5, color='teal')
# Horizontal Bar Chart
plt.barh(y, width, color='orange')
# Histogram
plt.hist(data, bins=10, color='green',
edgecolor='black')
# Customization (add before show)
plt.title("My Chart")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.legend()
plt.grid(True)
plt.xlim(0, 10)
plt.ylim(0, 100)
# Save & Display
plt.savefig("chart.png", dpi=300)
plt.show()
48.
R E VI S I O N K I T
Most Important Viva Questions
Q1. What is the difference between plt.show() and plt.savefig()?
Q2. Why must a colour name in matplotlib always be written in lowercase?
Q3. What happens if the x and y lists passed to plot() are of unequal length?
Difference in brief:
• plt.show() → Displays the chart on the screen (interactive window).
• plt.savefig() → Saves the chart to a file (e.g., PNG, PDF) for later use.
In short: show() = view, savefig() = store.
In Matplotlib, color names must be written in lowercase because the library’s internal color dictionary is
case-sensitive and only recognizes predefined lowercase strings (like "red", "blue", "green").
In short: lowercase ensures consistency and avoids errors when matching color names.
If the x and y lists passed to plot() are of unequal length, Matplotlib raises a ValueError because each x-value
must have a corresponding y-value.
In short: Unequal lengths → error (cannot plot).
49.
R E VI S I O N K I T
Most Important Viva Questions
Q4. How is a Histogram different from a Bar Chart? Give one example of each.
Q5. What is the purpose of the bins parameter in hist()?
Q6. Which function would you use to change the size of the figure before plotting?
A Histogram shows the frequency distribution of continuous data divided into intervals, while a Bar Chart
compares discrete categories.
Example:
•Histogram → Number of students scoring between 0–20, 21–40, 41–60, etc.
•Bar Chart → Number of students in Class 6, Class 7, Class 8.
The bins parameter in hist() decides how the data range is divided into intervals (bins). Each bin represents a
range, and the histogram shows how many values fall into each range.
In short: bins controls the number/width of intervals in a histogram.
You can change the figure size before plotting using the plt.figure(figsize=(width, height)) function in
Matplotlib.
50.
R E VI S I O N K I T
Previous Year Board-Style Questions
Practice these exam-pattern questions (based on past CBSE trends):
1 Mark: Which pyplot function is used to draw a horizontal bar graph? [1]
2 Marks: Write the output of: plt.plot([1,2,3],[4,5,6]); plt.show() — describe what will appear. [2]
3 Marks: Write a program to plot a bar chart for 5 subjects and their marks, with proper title and axis labels. [3]
plt.barh()
import matplotlib.pyplot as plt
# Data
subjects = ['Maths', 'Science', 'English', 'History', 'Computer']
marks = [85, 78, 92, 74, 88]
# Plot bar chart
plt.bar(subjects, marks, color='skyblue')
# Add title and axis labels
plt.title("Marks Obtained in 5 Subjects")
plt.xlabel("Subjects")
plt.ylabel("Marks")
# Show chart
plt.show()
51.
R E VI S I O N K I T
Previous Year Board-Style Questions
4 Marks: Differentiate between plt.bar() and plt.hist() with one example each. [4]
Difference between plt.bar() and plt.hist() (4 Marks):
• plt.bar() → Used to plot a bar chart for discrete categories.
• plt.hist() → Used to plot a histogram for continuous data distribution divided into intervals (bins).
Examples:
import matplotlib.pyplot as plt
# Example of Bar Chart
subjects = ['Maths', 'Science', 'English', 'History', 'Computer']
marks = [85, 78, 92, 74, 88]
plt.bar(subjects, marks, color='skyblue')
plt.title("Bar Chart - Marks in Subjects")
plt.show()
# Example of Histogram
data = [12, 15, 17, 18, 19, 20, 21, 22, 22, 23, 24, 25, 25, 26, 27, 28, 30]
plt.hist(data, bins=5, color='lightgreen', edgecolor='black')
plt.title("Histogram - Frequency Distribution")
plt.show()
52.
R E VI S I O N K I T
Previous Year Board-Style Questions
5 Marks: Write a Python program using matplotlib to plot both a Line Chart and a Bar Chart for the same dataset, side by side,
with legends. [5]
import matplotlib.pyplot as plt
# Dataset
subjects = ['Maths', 'Science', 'English', 'History', 'Computer']
marks = [85, 78, 92, 74, 88]
# Create subplots (1 row, 2 columns)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))
# Line Chart
ax1.plot(subjects, marks, marker='o', color='blue', label='Marks')
ax1.set_title("Line Chart - Marks")
ax1.set_xlabel("Subjects")
ax1.set_ylabel("Marks")
ax1.legend()
# Bar Chart
ax2.bar(subjects, marks, color='green', label='Marks')
ax2.set_title("Bar Chart - Marks")
ax2.set_xlabel("Subjects")
ax2.set_ylabel("Marks")
ax2.legend()
# Adjust layout and show
plt.tight_layout()
plt.show()
53.
R E VI S I O N K I T
Competency-Based Questions
Application-oriented questions that test real understanding, not memorization:
1. A shopkeeper wants to show monthly sales trends across the year. Which chart should he use and why?
2. Your school wants to display the age distribution of 200 sports-day participants. Suggest a suitable chart and justify.
The shopkeeper should use a Line Chart because it clearly shows sales trends over time (months).
Reason: A line chart highlights rise and fall patterns across the year, making it easier to
observe seasonal changes and overall growth compared to just static values.
A Histogram is most suitable to display the age distribution of 200 sports-day participants.
Reason: A histogram groups ages into intervals (bins) (e.g., 5–10 years, 11–15 years, etc.) and shows how
many participants fall in each range, making it easy to see the overall distribution pattern.
54.
R E VI S I O N K I T
Competency-Based Questions
3. A weather app shows daily temperature for 30 days. Identify the best chart type, and write the key code line.
4. Given marks of 3 sections (A, B, C) in the same subject, design a chart that lets viewers compare all three at a glance.
The best chart type is a Line Chart, because it clearly shows how temperature changes day by day over 30 days.
Key code line:
plt.plot(days, temperature)
This plots the daily temperature trend across the month.
To compare marks of Sections A, B, and C in the same subject at a glance, the best choice is a Grouped Bar Chart.
Reason: It places bars for each section side-by-side under the same subject, making comparison easy.
Example Code:
import matplotlib.pyplot as plt
# Data
sections = ['A', 'B', 'C']
marks = [85, 78, 90]
# Plot grouped bar chart
plt.bar(sections, marks, color=['red','green','blue'])
plt.title("Marks Comparison of Sections A, B, C")
plt.xlabel("Sections")
plt.ylabel("Marks")
plt.show()
55.
R E VI S I O N K I T
Assertion–Reason Questions
Choose: (a) Both A and R true, R explains A (b) Both true, R does not explain A (c) A true, R false (d) A false, R true
Assertion (A): A histogram is used to show the frequency distribution of continuous data.
Reason (R): In a histogram, the bars are drawn with gaps between them, similar to a bar chart.
Answer: (c)
Assertion (A): plt.legend() displays a box identifying each plotted series by colour.
Reason (R): legend() automatically works even if no label= parameter was set in plot() or bar().
Answer: (c)
Assertion (A): plt.savefig() should be called before plt.show() to save the chart correctly.
Reason (R): plt.show() clears the current figure from memory after displaying it.
Answer: (a)
56.
R E VI S I O N K I T
Case Study Based Question
CASE STUDY
A school conducted a survey of screen-time (in hours) of 50 students during summer vacation. The IT teacher wants to (i) see the overall
distribution of screen-time, and (ii) compare the average screen-time of boys vs girls on the same chart.
(i) Which chart type is most suitable to show the overall distribution of screen-time? Name the pyplot function.
(ii) Which chart type would best compare boys vs girls average screen-time side by side? Name the pyplot function.
(iii) Write the code line to add a legend to the boys-vs-girls comparison chart.
(iv) Suggest one customization (title/label/color) that would make the chart clearer for a school report.
To see the overall distribution of screen-time → use a Histogram, as it groups students’ screen-time into ranges (bins).
compare average screen-time of boys vs girls → use a Grouped Bar Chart, showing both categories side-by-side for easy
comparison.
plt.legend()
This will display the labels (e.g., "Boys", "Girls") that you set in the label parameter of plt.bar() or plt.plot().
plt.legend()
plt.title("Average Screen-Time of Boys vs Girls")
57.
R E VI S I O N K I T
MCQs — Easy, Moderate & Difficult
EASY
Which library is used for plotting in
Python?
(a) numpy
(b) matplotlib
(c) pandas
Which function displays the chart?
(a) plt.show()
(b) plt.open()
(c) plt.view()
MODERATE
To draw bars of different widths, "width"
should be:
(a) a string
(b) a list
(c) a tuple only
Which parameter of hist() controls range
grouping?
(a) range
(b) bins
(c) group
DIFFICULT
Which combination correctly places
grouped bars side-by-side?
(a) same x for both
(b) pos and pos+w
(c) random x values
plt.savefig() called AFTER plt.show()
typically produces:
(a) sharper image
(b) (b) blank image
(c) (c) an error always
Answer: (b)
Answer: (a)
Answer: (b)
Answer: (b)
Answer: (b)
Answer: (b)
58.
R E VI S I O N K I T
Programming Practice Questions
Write complete Python programs (with import, data, chart, labels, and show) for:
1. Plot a line chart of the temperature of your city for 7 days of a week, with a title and axis labels.
2. Plot a bar chart comparing the population of 5 countries, with different colours for each bar.
3. Plot a histogram of the marks of 40 students (out of 50) using 8 bins, with edgecolor black.
4. Plot two line charts (Maths and Science marks of 5 students) on the same axes with a legend.
5. Plot a horizontal bar chart of the time (in hours) spent on 5 different hobbies in a week.
59.
R E VI S I O N K I T
Homework Assignment
TASK
▸ Collect the daily study hours of yourself for the last 7 days.
▸ Write a Python program to plot this data as BOTH a line chart and a bar chart.
▸ Add a proper title, x-label ("Day") and y-label ("Hours Studied") to each chart.
▸ Save both charts using plt.savefig() with meaningful filenames.
▸ Write 2 lines explaining which chart represents your data better, and why.
▸ Write a Python program to plot a line chart showing daily temperature for 7 days, with proper title and axis labels.
▸ Differentiate between a Line Chart and a Histogram with one example each.
▸ A survey records the average study hours of boys and girls in your class. Write a Python program to plot a Grouped Bar Chart
comparing both, with legends and axis labels.
▸ Write a Python program to plot a Histogram showing the distribution of daily study hours of 30 students. Add a suitable title and axis
labels.
▸ A company records quarterly sales for 4 regions (North, South, East, West). Write a Python program to plot a Grouped Bar Chart
comparing sales across regions, with legends and different colors for each quarter.
EXAM TIP
Submit your .py file along with both saved chart images (.png) — this mirrors how a practical-exam program is evaluated.
60.
R E VI S I O N K I T
Mini Project Idea
"MY CLASS DASHBOARD"
▸ Collect marks of your class in 3 recent tests (any subject)
▸ Chart 1 — Line chart showing YOUR OWN progress across the 3 tests
▸ Chart 2 — Bar chart comparing class average of each test
▸ Chart 3 — Histogram showing the distribution of marks in the latest test
▸ Combine all 3 charts into one PDF report with titles and labels
▸ Present your findings to the class in 2 minutes
EVALUATION CRITERIA
Correct chart choice • Clean code • Proper labels &
titles • Clear conclusions • Neat presentation
61.
R E VI S I O N K I T
Teacher's Classroom Activity
"CHART DETECTIVE" — 15 minute activity
▸ Step 1: Divide the class into groups of 4. Each group gets a real newspaper/magazine chart (or printed chart).
▸ Step 2: Groups identify the chart type (line/bar/histogram) and justify their answer in one sentence.
▸ Step 3: Each group writes the matplotlib code that COULD have generated a similar chart.
▸ Step 4: Groups swap code with another team and try to spot one deliberate error planted by the teacher.
▸ Step 5: Class discussion — which chart types were most common in the media samples, and why?
62.
"Every chart youcode is a story you help others see."
You now know how to turn raw numbers into powerful visual stories using Python and Matplotlib.
Keep practising — the best data scientists started exactly where you are today!
E N D O F C H A P T E R — P L O T T I N G W I T H P Y P L O T
Thank You