Ministry of Education & Skills Development
Thimphu Bhutan
Data Science - Matplotlib
Activity Book
Class XII ICT Curriculum
February 2023
Competency
Present a visual representation of a dataset by applying data analysis modules
in a programming language to communicate a message.
Objectives
● Explain the different types of plots available in Matplotlib.
● Use a relevant plot using Matplotlib for a given dataset.
● Plot graphs for a set of data using PyPlot sub-library.
● Interpret the chart for a given dataset using Matplotlib.
Content Scope
● Introduction to Matplotlib
● Import PyPlot module
● Plot types
○ plot()
○ scatter(), bar(), stem(), pie(), hist()
● Attributes of graphs
○ Markers, line
○ Labels, grid
○ Subplot, Annotations
● Plotting data from list (Python), array (NumPy) and DataFrame (Pandas)
● Project on data analysis using NumPy, pandas and matplotlib
Page 1
Overview
Activity # Activity Title Concept
● Importing matplotlib
● Adding labels and title to the plot
Plotting data from list ● scatter()
1 (Python) ● pie()
● subplots()
● plot()
● Importing numPy
● Using numpy function to create
and add arrays
Plotting data from ● Using the numpy function to find
2 array (NumPy)
the square of a number.
● plot()
● bar()
● Importing Pandas
● Reading csv file using
Plotting data from read_csv()
3 DataFrame(Pandas) ● hist()
● stem()
Page 2
Introduction to Matplotlib
Matplotlib is a plotting library for the Python programming language. It is used to
create a wide range of static, animated, and interactive visualizations in 2D and
3D. The library provides a large set of customizable visualization tools, including
line plots, scatter plots, bar plots, histograms, and many more.
Matplotlib was originally developed by John D. Hunter in 2003 and it is now the
most widely used plotting library for Python. It is an open-source library, which
means that it is free to use and modify, and has a large community of users and
developers.
One of the key features of Matplotlib is its ability to create high-quality plots that
can be easily customized to suit the needs of the user. For example, users can
change the colors, line styles, and marker styles of plots, as well as add labels,
titles, and other annotations. The library also provides support for interactive
plotting, so users can zoom, pan, and hover over plots to explore the data in
more detail.
Advantages of Matplotlib
We are living in a visual world, where pictures speak louder than words. Data
visualization is extremely important in every field of science, especially when it
comes to data science.
Some of the advantages of using Matplotlib include:
● Flexibility: Matplotlib allows you to create a wide range of plots, including
line plots, scatter plots, bar plots, histograms, and more. It also provides a
variety of customization options, such as changing the colors, line styles,
and marker styles of plots.
● Interactivity: Matplotlib supports interactive plotting, which allows you to
zoom, pan, and hover over plots to explore the data in more detail.
● Integration: Matplotlib can be easily integrated with other popular Python
libraries, such as NumPy and Pandas, making it easy to work with data in a
variety of formats.
● Community: Matplotlib is an open-source library and has a large
community of users and developers, which means that there are plenty of
resources available for learning and troubleshooting.
● Compatibility: Matplotlib is compatible with various operating systems and
can be used in a variety of environments, including Jupyter Notebooks,
IDLE, and PyCharm.
Page 3
Installation of Matplotlib
To use matplotlib, we need to install it.
1. In order to install matplotlib, one needs to ensure Python and pip are
preinstalled on your system.
2. Matplotlib can be installed using pip. The following commands are run in
the command prompt to install Matplotlib.
In windows In mac
1. Open cmd 1. Open terminal
2. Run the following command 2. Run the following command
pip install --upgrade pip pip3 install --upgrade pip
pip install matplotlib pip3 install matplotlib
Links to Matplotlib Resources
Here is a list of resources that you can use to learn more about Matplotlib in
python.
1. This site provides user guide, tutorial and references on Matplotlib:
[Link]
2. Link to source code of all activities
[Link]
3. Matplotlib tutorial- includes basic to advanced concepts of Matplotlib:
[Link]
4. Detailed explanation and practice questions with solutions:
[Link]
5. Python tutorial for beginners:
[Link]
6. Graphing plotting in python:
[Link]
7. Matplotlib (Python Plotting Library)
[Link]
8. Crash course on data analysis
[Link]
Page 4
Activity 1: Plotting data from list (Python)
Objectives:
● Generate a graph for a dataset using the pyplot module.
● Identify the advantages of representing data in graphical format for data
analysis.
● Use different plots based on the data
Information Input
The list data type in python can be used to store sets of data that can be plotted
using matplotlib functions, such as plot(), scatter(), and hist(), pie() etc.
Task 1:
The students in a science class conducted an experiment in which they added
different masses to the top of a spring. Write a python program to draw a
scatter plot to display their data.
Mass added Length of spring
(kg) (cm)
0 15.0
2 13.2
4 11.4
6 9.6
8 7.8
10 6.0
Sample Code - link
Page 5
Output
Note for Teachers
● Highlight that list data can be represented in plot
● Explain in what type of data scatter plot can be used
○ Scatter plots can be used to identify the correlation between
two variables, positive, negative or none correlation.
● Explain the relationship between the data
● Unlike Numpy and Pandas, we use ‘import [Link]
as plt’, this is because ‘pyplot’ is not a built-in method of Matplotlib,
therefore we will need to access all the plots (graphs) which are
included as a module of Matplotlib.
Page 6
Task 2:
Write a python program to generate a pie chart for the percent of time teens in
a school in Thimphu spend on Leisure Activities.
Activity Time spent (%)
Games 15
Reading 5
TV 70
Song and Dance 5
Others 5
Sample Code - link
Output
Page 7
Note for Teachers
● Pie charts are useful when you want to compare the proportion or
percentage of different categories or groups of data.
● Explain the autopct parameter:
○ It is used in the pie() function to format the value of each pie
slice as a percentage.
○ It takes a string format or a function as its [Link] example, if
you want to display the percentage values rounded to two
decimal places, you can set autopct='%.2f%%'. This will display
the values as [Link]%.
Task 3:
Write a python program to generate a multiple line graph for the number of
students by gender in four classes.
Class Male Female
Class I 23 19
Class II 16 21
Class III 19 18
Class IV 17 23
Sample Code - link
Page 8
Output
Note for Teachers
● Explain the concept of subplot().
○ A subplot is a way to create multiple plots within a single figure.
● Explain that the plot() function is used to draw the line graph
connecting all the points.
● Explain the following points:
○ fig is a handle to the created figure, which you can use to
customize the overall appearance of the figure, such as adding
a title, changing the size, or saving the figure to a file.
○ ax is a handle to the created subplot, which you can use to
customize the appearance of the subplot, such as adding labels,
changing the limits, or plotting data on the subplot.
● Suggest other plot types that are applicable for this kind of data.
Page 9
Activity 2: Plotting data from array (NumPy)
Objectives:
● Generate a graph for a given array importing the numpy library.
● Use the functions in numpy to create an array and add the two arrays
● Use numpy and matplotlib together to display the data
Information Input
Numpy is a library for numerical computing and provides useful functions for
working with arrays and matrices, while matplotlib is a library for plotting and
visualizing data. Together, they can be used to create powerful data visualization
tools.
Numpy array function is used to create arrays for x and y variables while the
matplotlib function plot is used to draw a line graph.
Task 1:
Write a python program to generate a graph for the function y = x2 . Complete
the table of value given below.
x -3 -2 -1 0 1 2
y = x2
Sample Code - link
Page 10
Output
Note for Teachers
● Explain the use of the numpy function in finding the square of a
number.
● Explain that the plot function is used to draw a line graph.
● Explain and demonstrate the advantages of using numpy with
matplotlib.
● Suggest other plot types that are applicable for this kind of data.
Task 2:
Write a Python program to generate a Bar chart to represent the total of CA and
Exam marks given in the table. Use Numpy to convert the marks obtained in CA
and Exam in arrays and add them.
Name of student Karma Tshering Sonam Pema KInley
CA(10) 8.5 9 8 7 8.5
Exam(50) 38 45.5 40 39 35
Page 11
Sample Code - link
Output
Note for Teachers
● Explain that the numpy function add is used to calculate the total marks
obtained by the students.
● Explain about the Bar chart and where it can be used.
● Explain the advantages of using numpy with matplotlib
● Suggest other plot types that are applicable for this kind of data.
Page 12
Activity 3: Plotting data from DataFrame (Pandas)
Objectives:
● Generate graph for a csv file importing pandas library.
● Integrate pandas and matplotlib together to display the data visually
Information Input
The pandas library provides an easy way to work with tabular data, while
matplotlib provides a wide variety of plotting and visualization capabilities, and
the two libraries can be used together to easily create various types of plots and
visualizations of data.
One of the most common ways to use pandas and matplotlib together is to first
load your data into a pandas dataframe, and then use the various plotting
functions provided by matplotlib to create visualizations of the data.
Task 1:
Write a python program to check the frequency distribution using histogram plot
for the total number of tourists arrived in the year 2018.
Sample Code - link
Page 13
Output
Note for Teachers
● Explain how the pandas library is used to import the csv file into
matplotlib to draw the stem plot.
● Explain the parameters used such as bins and color and the function
xticks() referring to the table attached at the end.
● Explain the advantages of using Pandas with matplotlib
Page 14
Task 2:
Write a python program to display the total number of tourist arrivals in Bhutan
in 2018 using the pandas function to import the data from
'Tourist_Arrival_2018.csv' and then plot it in the form of a stem plot.
Sample Code - link
Output
Note for Teachers
● Explain how the pandas library is used to import the csv file into
matplotlib to draw the stem plot.
● Explain the parameters used such as markerfmt, linefmt, basefmt
referring to the table attached at the end.
● Suggest other plot types that are applicable for this kind of data.
Page 15
List of functions and attributes:
Sl# Functions/ Description
Attributes
1 The plot function is used to create a basic line plot.
plot()
2 xlabel() Adds labels to the x-axis.
3 ylabel() Adds labels to the y-axis
4 title() Adds title to the plot.
5 show() Displays the plot.
The scatter() function plots one dot for each
6 scatter()
observation. It needs two arrays of the same length.
7 bar() It plots a bar graph for the given data set.
The stem() function is used to create a stem plot.
8 stem() It consists of a set of vertical lines (stems) and dots
(markers) that represent the data points.
The pie() method takes several arguments, including the
9 pie() data to be plotted, the labels for the data, and the colors
to be used for each section of the pie chart.
10 hist() The hist() function is used to plot a histogram.
11 legend() adds a legend to the chart
12 grid() adds a grid to the chart
13 annotate() adds an annotation to the chart
14 text() adds text annotations to the chart
15 subplot() draw multiple plots in one figure:
16 color sets the color of the bars
17 alpha sets the transparency of the histogram
18 bins sets the number of bins used in the histogram
It is used to add a shadow effect to the pie chart.
19 shadow
Page 16
sets whether the histogram represents the probability
20 density
density function or not
It is used to format the value of each wedge as a
21 autopct
percentage.
22 markerfmt sets the marker style for the stem plot
23 basefmt sets the format for the baseline of the stem plot
Data Science Final Project
Write a Python program to analyze the marks scored in mathematics, english
and science for class X conducted by BCSEA. The analysis should include the
following subtasks
1. Import all the necessary libraries for data analysis - NumPy, Pandas,
Matplotlib.
2. Load the dataset in CSV format using pandas.
3. Use pandas to inspect the dataset.
a. Print first five and bottom five data to see the consistencies of the
data
b. Check data types and missing values
4. Clean and prepare the dataset using pandas.
a. Remove the rows with missing values
b. Remove the rows having zero (0) as marks
5. Use pandas to do the following calculations.
a. Sort the data into descending order based on the Mathematics
mark.
b. Display the top ten performers.
c. Find out the mark that is scored by the maximum number of
students in a Science subject.
d. Find the correlation coefficient between Mathematics and Science
subjects. Interpret the correlation coefficient.
6. Use NumPy to perform mathematical operations on the data.
a. Find the mean and median marks of each subject separately.
b. Calculate the standard deviation for each subject.
c. Interpret the significance of the standard deviation.
7. Using a Matplotlib, generate a scatter plot for Mathematics and Science
subjects with a line of best fit in the plot. Interpret the plot.
8. Calculate the mean of three subjects and plot a bar chart. Which subject is
done better in general?
Page 17