0% found this document useful (0 votes)
31 views29 pages

Ch 4 Plotting Data Using Mathplotlib 2024-25

Uploaded by

reduxotter
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
31 views29 pages

Ch 4 Plotting Data Using Mathplotlib 2024-25

Uploaded by

reduxotter
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

Chapter 4

Plotting Data using Matplotlib

Syllabus 2024-25 :
 Purpose of plotting;
 drawing and saving following types of plots using Matplotlib
 line plot, bar graph, histogram
 Customizing plots: adding label, title, and legend in plots.

1. What do you understand by Data Visualization?


Ans. Data visualization is the technique to present the data in a pictorial or
graphical format. It enables stakeholders and decision makers to analyze
data visually.
The data in a graphical format allows them to identify new trends and
patterns easily.
2. Write the benefits of Data Visualization.
Ans.  It simplifies the complex quantitative information.
 It helps analyze and explore big data easily.
 It identifies the areas that need attention or improvement.
 It identifies the relationship between data points and variables.
 It explores new patterns and reveals hidden patterns in the data.
3. Write the three major considerations for data visualization.
Ans. Three Major considerations for Data Visualization -
• Clarity - ensures that the data set is complete and relevant. This enables the
data scientist to use the new patterns yield from the data in the relevant places.
• Accuracy - ensures using appropriate graphical representation to convey
the right message.
• Efficiency - uses efficient visualization technique which highlights all
the data points.
4. Name some recently introduced Python Data Visualization Libraries.
Ans.  Many new Python Data Visualization Libraries are introduced
recently, such as matplotlib, Vispy, bokeh, Seaborn, pygal, folium, and
networkx.
 The matplotlib has emerged as the main data visualization library.
5. What is Matplotlib?
Or,
What is the purpose of using Matplotlib in Python?
Ans.  Matplotlib is a python two-dimensional plotting library for data
visualization and creating interactive graphics or plots. Using pythons
Introduction to Data Visualization – Class Notes, 2024-25

matplotlib, the data visualization of large and complex data becomes


easy.
 Matplotlib is one of the most popular and widely used data visualization
library in Python.
 It produces quality figures in a variety of hard copy formats and
interactive environments across platforms.
 Matplotlib can be used in Python scripts, IPython shell, jupyter
notebook, web application servers, and for GUI toolkits.
 To create impactful visualization with python, matplotlib is an essential
tool.
6. Write the advantages of using Matplotlib.
Ans.  A multi-platform data visualization tool built on the numpy and sidepy
framework. Therefore, it's fast and efficient.
 It possesses the ability to work well with many operating systems and
graphic backends.
 It possesses high-quality graphics and plots to print and view for a
range of graphs such as Histograms, Bar charts, Pie charts, Scatter
plots and Heat maps.
 It has large community support and cross-platform support as it is
an open source tool.
 It has full control over graph or plot styles such as line properties,
thoughts, and access properties.
7. How to install matplotlib?
Ans. Install matplotlib by pip command in command prompt as – pip install
matplotlib
8. What is Pyplot?
Or,
What is the used of Pyplot in matplotlib?
Ans. Matplotlib has a module called pyplot which aids in plotting figure.
Pyplot is a module in matplotlib, which supports a very wide variety of
graphs and plots namely - histogram, bar charts, power spectra, error charts
etc. It is used along with NumPy to provide an environment for MatLab.
9. Write the statement to call pyplot module.
Ans. import matplotlib.pyplot as plt for making it call the package module.
10. What do you understand by the term - Plot?
Ans. A Plot is a graphical representation of data, which shows the relationship
between two variables or the distribution of data.
10. Write the features of providing in matplotlib library for data visualization.
Ans. Following features are provided in matplotlib library for data visualization-
• Drawing Plot
• Customizing Plot
• Saving Plot

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 2
Introduction to Data Visualization – Class Notes, 2024-25

Drawing Plots can be drawn based on passed data through specific


functions.
Customization Plots can be customized as per requirement after specifying
it in the arguments of the functions like color, style (dashed, dotted); width,
adding lable, title and legend in plots
Saving – After drawing and customization plots can be saved for future use.
11. Write the five steps for building plot.
Ans. Five steps for building plot are-
 Step1 : Imports modules
 Step 2 : Define data
 Step 3 : Plot data including options
 Step 4 : Add plot details
 Step 5 : Show the plot
12. Write the different types of plot using matplotlib.
Ans. To create different types of plots using matplotlib:
• Line Plot
• Bar Graph
• Histogram
• Scatter Plot
• Heat Map
• Pie Chart
• Error Bar
13. What is Line Plot?
Ans.  A line plot or line chart or line graph is a type of chart which displays
information as a series of data points called ‗markers‘ connected by
straight line segments.
 Line graphs are usually used to find relationship between two data sets
on different axis; for instance X, Y.
 A line plot is often used to visualize a trend in data over intervals of time.
14. How to create Line Plot?
Ans. A line plot can be created using plot() function available in PyPlot library.

15. Write a program to draw single line chart.


Ans. #Program to draw single line
import matplotlib.pyplot as plt
x = [2, 4, 6]
y = [1, 3, 5]
plt.plot(x, y)
plt.show()

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 3
Introduction to Data Visualization – Class Notes, 2024-25

16. Write a program to draw single line along with proper labels, titles and
legends.
Ans. import matplotlib.pyplot as plt
x = [1,2,3] # x axis values
y = [2,4,1] # corresponding y axis values
plt.plot(x, y) # plotting the points
plt.xlabel('x - axis') # naming the x axis
plt.ylabel('y - axis') # naming the y axis
plt.title('My First Graph!') # giving a title to my graph
plt.legend() #involves a legend
plt.show() # function to show the plot

17. Write a program to draw two lines along with proper labels, titles and
legends.

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 4
Introduction to Data Visualization – Class Notes, 2024-25

Ans. import matplotlib.pyplot as plt


x = [1,2,3]
y = [5,7,4]
plt.plot(x,y,label = 'First line') #Plotting two lists with
appropriate label
x2 = [1,2,3]
y2 = [10,11,14]
plt.plot(x2,y2,label= 'Second line')
plt.xlabel('Plot number')
plt.ylabel('Important variables')
plt.title('New Graph')
plt.legend() #involves a legend
plt.show() #Displaying the chart

18. Write a program to draw Multiple lines with multiple colors given explicitly
using numpy.
Ans. import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1, 3)
plt.plot(y, 'y')
plt.plot(y+1, 'm')
plt.plot(y+2, 'c')
plt.show()

19. Write a program to exhibit different line styles using numpy.


Ans. import matplotlib.pyplot as plt
import numpy as np
y = np.arange(1, 3)
plt.plot(y, '--', y+1, '-.', y+2, ':')
plt.show()

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 5
Introduction to Data Visualization – Class Notes, 2024-25

20. Write a program to draw two or more lines with different widths and colors
with suitable legends.
Ans. import matplotlib.pyplot as plt
x1 = [10,20,30] # line 1 points
y1 = [20,40,10]
x2 = [10,20,30] # line 2 points
y2 = [40,10,30]
plt.xlabel('x - axis') # Set the x axis label of the current
axis
plt.ylabel('y - axis') # Set the y axis label of the current
axis.
# Set a title
plt.title('Two or more lines with different widths and
colors with suitable legends')
# Display the figure.
plt.plot(x1,y1, color='blue', linewidth = 3, label =
'line1-width-3')
plt.plot(x2,y2, color='red', linewidth = 5, label = 'line2-
width-5')
plt.legend() # show a legend on the plot
plt.show()

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 6
Introduction to Data Visualization – Class Notes, 2024-25

21. Write the various arguments or parameters of plt.plot() method of Line


Chart.
Ans. plt.plot(<x-data>, <y-data>,
linewidth=<float or int>,
linestyle='<linestyle abbreviation>‘,
color='<color abbreviation>‘,
marker='<marker abbreviation>‘,
markeredgecolor='<color abbr>’
markerfacecolor='<color abbr>’
markersize=<float or int>)

Linestyle values
'-' or 'solid' solid line (default)
'--' or 'dashed' dashed line
'-.' or 'dashdot' dash-dot line
':' or 'dotted' dotted line
'None' or ' ' or '' no line

Color values Marker


'b' blue '.' point

'c' cyan ',' one pixel

'g' green 'o' circle


'*' star
'k' black
'+' plus
'm' magenta
'P' filled plus
'r' red
'x' x
'w' white
'X' filled x
'y' yellow

22. How to customise or add details to the plot such as title, axis, labels, legend,
grid etc. after plt.plot() line?
Ans. After the plt.plot() line, add details such as a title, axis labels, legend, grid,
and tick labels.
• plt.title('<title string>‘)
• plt.xlabel('<x-axis label string>‘)
• plt.ylabel('<y-axis label string>‘)
• plt.legend(['list','of','strings'])
• ptl.grid(<True or False>)

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 7
Introduction to Data Visualization – Class Notes, 2024-25

 The plot title will be shown above the plot.


 The x-axis label is shown below the x-axis.
 The y-axis label is shown to the left of the y-axis.
 The legend appears within the plot area, in the upper right corner by
default.
 A grid can be added to a plot.By defaut, the grid is turned off.
 To turn on the grid use: plt.grid(True)
23. What is used of show() command?
Ans.  plt.show() command to show the plot.
 plt.show() causes the plot to display or pop out in a new window if the
plot is constructed in a separate .py file.
 plt.show() needs to be called after plt.plot() and any plot details such
as plt.title()
24. What is bar chart?
Ans.  A bar chart or bar graph is a chart or graph that presents categorical
data with rectangular bars with heights or lengths proportional
to the values that they represent.
 The bars can be plotted vertically or horizontally.
 A bar graph shows comparisons among discrete categories. One axis of
the chart shows the specific categories being compared, and the other axis
represents a measured value.

25. Which function is used to draw bar graph with pylot module?
Ans. With Pyplot, you can use the bar() or barh() function to draw bar graphs.
26. Write the function to draw vertical and horizontal bars with its arguments.

Ans. The bar() function takes arguments that describes the layout of the Vertical
bars. Syntax-
plt.bar(x, y, width, color)
The barh() function takes arguments that describes the layout of the
Horizontal bars. Syntax-
plt.barh(x, y,height,color)

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 8
Introduction to Data Visualization – Class Notes, 2024-25

27. What is the default width and height of the vertical and horizontal bars
respectively?
Ans. The default width of the Vertical bar is 0.8
The default height of the Horizontal bar is 0.8
28. Write a program to draw four vertical bars.
Ans. #Program to draw 4 vertical bar
import matplotlib.pyplot as plt
x = ["A", "B", "C", "D"]
y = [3, 8, 1, 10]
plt.bar(x,y)
plt.show()

29. Write a program to draw four very thin vertical bars.


Ans. import matplotlib.pyplot as plt
x = ["A", "B", "C", "D"]
y = [3, 8, 1, 10]
plt.bar(x,y,width=0.1)
plt.show()

30. Write a program to draw four horizontal bars.

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 9
Introduction to Data Visualization – Class Notes, 2024-25

Ans. import matplotlib.pyplot as plt


x = ["A", "B", "C", "D"]
y = [3, 8, 1, 10]
plt.barh(x,y)
plt.show()

31. Write a program to draw 4 horizontal very thin bars.


Ans. import matplotlib.pyplot as plt
x = ["A", "B", "C", "D"]
y = [3, 8, 1, 10]
plt.barh(x,y,height=0.1)
plt.show()

32 Write a program to draw 4 vertical bar color, using color as red.


Ans. import matplotlib.pyplot as plt
x = ["A", "B", "C", "D"]
y = [3, 8, 1, 10]
plt.bar(x,y,color=‘red’)
plt.show()

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 10
Introduction to Data Visualization – Class Notes, 2024-25

33. What is a Histogram in matplotlib?


Ans.  A histogram is a graph showing frequency distributions.
 It is a graph showing the number of observations within each given
interval.
 It is similar to a vertical bar graph but without gaps between the bars.
 In Matplotlib, we use the plot.hist() function to create histograms and
specify the number of bins (range of values).
34. What are bins in histogram?
Or,
What is the significant of bins in Histogram?
Ans.  To construct a histogram, the first step is to “bin” the range of
values — that is, divide the entire range of values into a series of
intervals — and then count how many values fall into each interval.
 The bins are usually specified as consecutive, non-overlapping
intervals of a variable.
 For a histogram, the bins (intervals) must be adjacent and equal size
i.e. the width should be the same across all bars.
35. How the histogram is differing from bar plot?
Ans. Histogram is constructed without gaps between the bars whereas bar graphs
contain gaps between the bars.
36. Write a program to plot a simple histogram of random values.
Ans. import matplotlib.pyplot as plt
import numpy as np
y = np.random.randn(1000)
#y = np.random.normal(170,20,200)
plt.hist(y)
plt.show()

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 11
Introduction to Data Visualization – Class Notes, 2024-25

37. Write a program to plot a histogram with different formatting and suitable
title and labels and also to save the Graph/plot to the default location i.e.
source file location.
Ans. import numpy as np
import matplotlib.pyplot as plt
data_students=[1,11,21,31,41,51]
plt.hist(data_students,bins=[0,10,20,30,40,50,60],weights=[1
0,1,0,33,6,8],facecolor='yellow',edgecolor="red")
plt.title("Histogram for Students data“, fontsize=15)
plt.xlabel('Value‘, fontsize=15)
plt.ylabel('aFrequency‘, fontsize=15)
plt.savefig("student.png") #Save graph
plt.show()

38. What do you meant by Saving plots?


Or,
Name the function that can be used to save the Matplotlib plots.

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 12
Introduction to Data Visualization – Class Notes, 2024-25

Or,
Name the different image file format that can be used to save the Matplotlib
plot.
Or,
What is dpi argument in savefig() function?
Ans.  Matplotlib plots can be saved as image files using
the plt.savefig() function and gets saved in the current working
directory.
 The plt.savefig() function needs to be called right above
the plt.show() line.
 All the features of the plot must be specified before the plot is saved as an
image file.
 If the figure is saved after the plt.show() command; the figure will not
be saved until the plot window is closed.
plt.savefig(image.png,dpi=300)
 Image file format (.png, .jpg, .svg. .pdf etc) based on the extension
specified in the filename.
 dpi stands for dots per inch : dpi=300 specifies how many dots per
inch (image resolution) are in the saved image.
 Example:
plt.savefig(‘plot.pdf')
plt.savefig(‘plot.svg‘)
plt.savefig(‘plot.png')
39. Write a program to save a plot in .png format.
Ans. import matplotlib.pyplot as plt
x = [0, 2, 4, 6]
y = [1, 3, 4, 8]
plt.plot(x,y)
plt.xlabel('x values')
plt.ylabel('y values')
plt.title('plotted x and y values')
plt.legend(['line 1'])
# save the figure
plt.savefig('plot.png', dpi=300, bbox_inches='tight')
plt.show()

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 13
Introduction to Data Visualization – Class Notes, 2024-25

40. Write the various graph methods used with matplotlib.pyplot modules.
Ans. Line Plot – plt.plot()
Vertical Bar Plot – plt.bar()
Horizontal Bar Plot – plt.barh()
Histogram – plt.hist()

41. How to plot dataframe using Pandas?


Ans. We can plot a dataframe using the plot() method. But we need a
dataframe to plot. We can create a dataframe by just passing a
dictionary to the DataFrame() method of the pandas library.
42. Name the method to create variety of graphs of Pandas objects?
Ans. plot() method of pandas objects.
It allows customising different plot types by supplying the kind
keyword arguments.
The general syntax is:
plt.plot(kind), where kind accepts a string indicating the type of plot,
Example:
df.plot(kind=’bar’)
43. What is an Open Data?
Ans. There are many websites that provide data freely for anyone to
download and do analysis, primarily for educational purposes. These
are called Open Data as the data source is open to the public.
Availability of data for access and use promotes further analysis and
innovation.
―Open Government Data (OGD) Platform India‖ (data. gov.in) is a
platform
for supporting the Open Data initiative of the Government of India.

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 14
Introduction to Data Visualization – Class Notes, 2024-25

TEXT BOOK QUESTIONS - SOLVED


1. What is the purpose of the Matplotlib library?
Ans. Matplotlib library is used for creating static, animated, and
interactive 2D- plots or figures in Python.
2. What are some of the major components of any graphs or plot?
Ans. Major components of graphs or plot are –
plotting area, legend, axis labels, ticks, title etc.
3. Name the function which is used to save the plot.
Ans. pyplot.savefig('x.png')
4. Write short notes on different customisation options available with
any plot.
Ans. Different customisation options with any plot are -
Grid () - Configure the grid lines.
legend() - Place a legend on the axes.
savefig() - Save the current figure.
show() - Display all figures.
title() - Set a title for the axes.
xlabel() - Set the label for the x-axis.
xticks() - Get or set the current tick locations and labels of the x-
axis.
ylabel() - Set the label for the y-axis.
yticks() - Get or set the current tick locations and labels of the y-
axis.
5. What is the purpose of a legend?
Ans. A legend is an area describing the elements of the graph. In the
matplotlib library, there‘s a function called legend() which is
used to Place a legend on the axes.
6. Define Pandas visualisation.
Ans. Pandas or Data visualisation is the technique to present the data
in a pictorial or graphical format. It enables stakeholders and
decision makers to analyze data visually.
7. What is open data? Name any two websites from which we can
download open data.
Ans. There are many websites that provide data freely for anyone to
download and do analysis, primarily for educational purposes.
These are called Open Data as the data source is open to the
public. Availability of data for access and use promotes further
analysis and innovation.
Example of open data download from Indian‘s websites are-
https://www.data.gov.in, https://sikkim.data.gov.in/,
https://surat.data.gov.in/,
http://opendata.punecorporation.org/Citizen/User
8. Give an example of data comparison where we can use the scatter
plot.
Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 15
Introduction to Data Visualization – Class Notes, 2024-25

Ans. Not in Syllabus


9. Name the plot which displays the statistical summary.
Ans. Not in Syllabus
10. Plot the following data using a line plot:
Day 1 2 3 4 5 6 7
Tickets 2000 2800 3000 2500 2300 2500 1000
Sold
 Before displaying the plot display ―Monday, Tuesday,
Wednesday, Thursday, Friday, Saturday, Sunday‖ in place of
Day 1, 2, 3, 4, 5, 6, 7
 Change the color of the line to ‗Magenta‘.
Ans. import pandas as pd
import matplotlib.pyplot as plt
x=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]
y=[2000,2800,3000,2500,2300,2500,1000]
plt.plot(x,y,color="magenta",marker="*", label="No.
of tickets")
plt.title("Day wise Tickets sold ")
plt.xlabel("Days")
plt.ylabel("No of tickets sold")
plt.legend()
plt.grid(True)
plt.savefig("d:\ Tickets.jpg")
plt.show()

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 16
Introduction to Data Visualization – Class Notes, 2024-25

BOARD QUESTIONS AND ANSWERS


Year : 2020-24
1. Fill in the blank with the correct statement to plot a bar graph using a
matplotlib method, so that Company ABC can see the graphical
presentation of its Profit figures for the 2nd quarter of the financial year
2019 (i.e. August, September, October, November).
[Comptt. 2020, 1 Marks]

import matplotlib.pyplot as mtp


Months = ['AUG', 'SEP', 'OCT', 'NOV'] #X Axis
Profits = [125, 220, 230, 175] #Y Axis
_________________________________
mtp.show()
Ans. mtp.bar(Months, Profits)
2. The table below shows the Marks of two students for the four unit tests for
academic session 2019-2020. Fill in the blanks to draw a line graph with
Test Names on the X axis and Marks on the Y axis.

[Comptt. 2020, 2 Marks]


import matplotlib.pyplot as plt
Tests = __________________ #Assign Test Names
Rohit = __________________ #Assign Marks of Rohit
Suman = __________________ #Assign Marks of Suman
plt.plot(Tests, Rohit, Suman)
_____________ #Label Y axis as Marks
_____________ #Add legends "Rohit", "Suman" for the lines
plt.show()
Ans. ['Unit1','Unit2','Unit3','Unit4']
[85,88,89,87]
[97,99,90,92]
plt.ylabel('Marks')
plt.legend(['Rohit','Suman'])
3.
Ans.
4. Write the output from the given Python code :
[CS, Comptt. 2020, 2 Marks]

import matplotlib.pyplot as plt


Months = ['Dec','Jan','Feb','Mar']
Marks = [70, 90, 75, 95]
plt.bar(Months, Attendance)

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 17
Introduction to Data Visualization – Class Notes, 2024-25

plt.show()
Ans.

5. Fill in the blanks : [SQP, 2020-21, 1 Mark]


The command used to give a heading to a graph is _________
a. plt.show()
b. plt.plot()
c. plt.xlabel()
d. plt.title()
Ans. d. plt.title()
6. Using Python Matplotlib _________ can be used to count how many values
fall into each interval. [SQP, 2020-21, 1 Mark]
a. Line plot
b. Bar graph
c. Histogram
Ans. c. Histogram
7. Consider the following graph. Write the code to plot it.
[SQP, 2020-21, 3 Mark]

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 18
Introduction to Data Visualization – Class Notes, 2024-25

Ans. import matplotlib.pyplot as plt


plt.plot([2,7],[1,6])
plt.show()

Alternative answer :

import matplotlib.pyplot as plt


a = [1,2,3,4,5,6]
b = [2,3,4,5,6,7]
plt.plot (a,b)
8. Draw the following bar graph representing the number of students in each
class. [SQP, 2020-21, 3 Mark]

Ans. import matplotlib.pyplot as plt


Classes = ['VII','VIII','IX','X']
Students = [40,45,35,44]
plt.bar(classes, students)
plt.show()
9. Fill in the blank with the correct statement to plot a bar graph
using a matplotlib method, so that Company ABC can see the
graphical presentation of its Profit figures for the 2nd quarter of
the financial year 2019 (i.e. August, September, October,
November). [AI, 2021, 1 Marks]
import matplotlib.pyplot as mtp
Months = ['AUG', 'SEP', 'OCT', 'NOV'] #X Axis
Profits = [125, 220, 230, 175] #Y Axis

mtp.show()
Ans. mtp.bar(Months, Profits)
10. A pie chart is to be drawn (using pyplot) to represent Population of
States. Fill in the blank with correct statement using a matplotlib
method to draw the pie chart with labels for the pie slices as the
names of the States and the size of each pie slice representing the
corresponding Population of the States (in crores), as per the
following table : [AI, 2021, 1 Marks]

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 19
Introduction to Data Visualization – Class Notes, 2024-25

import matplotlib.pyplot as plt


States = ['Rajasthan','Karnataka','Tamilnadu','Goa']
Population = [6.8,6.1,7.2,1.5]

plt.show()
Ans. plt.pie(Population, labels=States)
11. The table below shows the Marks of two students for the four unit
tests for academic session 2019-2020. Fill in the blanks to draw a
line graph with Test Names on the X axis and Marks on the Y
axis. [AI, 2021, 2 Marks]

import matplotlib.pyplot as plt


Tests = #Assign Test Names
Rohit = #Assign Marks of
Rohit
Suman = #Assign Marks of
Suman
plt.plot(Tests, Rohit, Suman)
#Label Y axis as Marks
#Add legends "Rohit", "Suman" for the lines
plt.show()
['Unit1','Unit2','Unit3','Unit4']
[85,88,89,87]
[97,99,90,92]
plt.ylabel('Marks') plt.legend(['Rohit','Suman'])
12. a) Consider the following graph. Write the code to plot it. Also label
the X and Y axis. . [AI, 2021, Compt, 3 Marks]

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 20
Introduction to Data Visualization – Class Notes, 2024-25

Ans. import matplotlib.pyplot as


pltX=[1,2,3,4,5]
Y=[12,14,13,15,19]
plt.plot(X,Y)
plt.xlabel('Tests')
plt.ylabel('Marks
secured')plt.show()

b) Write code to draw the following bar graph representing the total
number of medals won by Australia. [AI, 2021, Compt, 3 Marks]

Ans. import matplotlib.pyplot as plt


X=['Gold','Silver','Bronze','Total']
Y=[75,50,50,200] plt.bar(X,Y)
plt.xlabel('Medals won by Australia')
plt.ylabel('Medals won')
plt.title('AUSTRALIA MEDAL PLOT')
plt.show()
13. What is Data Visualization ? Discuss briefly. Also mention the
name of one of the most commonly used Python library for data
visualization. [AI, 2021, Compt, 3 Marks]

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 21
Introduction to Data Visualization – Class Notes, 2024-25

Ans. Data visualization is the graphical representation of information


and data. Data visualization is another form of visual art that
grabs our interest and keeps our eyes on the message.
Most commonly used Python Library for data visualization is
matplotlib
14. Mention the purpose of the following functions briefly :
i) plot()
ii) show()
iii) savefig() [AI, 2021, Compt, 3 Marks]
Ans. i) The plot() function draws a line from point to point. The
function takes the following parameters for specifying points in
the diagram : first parameter is an array containing the points
on the x-axis the second parameter is an array containing the
points on the y-axis
ii) The show() function in the pyplot module of matplotlib library
is used to display all figures.
iii) The savefig() method is used to save the figure created after
plotting data. The figure created can be saved to our local
machines by using this method.
15. Which library is imported to draw charts in Python ?
a) csv
b) numpy
c) matplotlib
d) pandas [AI, 2021, Term 1, 1 Mark]
Ans. c) matplotlib
16. Which of the following command is used to import matplotlib for
coding?
a) import matplotlib.pyplot as plt
b) import py.matplotlib as plt
c) import plt.matplotlib as plt
d) import pyplot.matplotlib as plt
[AI, 2021, Term 1, 1 Mark]
Ans. a) import matplotlib.pyplot as plt

17. Consider the following statements with reference to Line charts


Statement – A Line graphs is a tool for comparison and is created by
plotting a series of several points and connecting them with a straight line.
Statement – B You should never use line chart when the chart is in a
continuous data set. [AI, 2021, Term 1, 1 Mark]
a) Statement A is correct
b) Statement A is correct but Statement B is incorrect
c) Statement B is correct
d) Statement A is incorrect, but Statement B is correct
Ans. b) Statement A is correct but Statement B is incorrect

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 22
Introduction to Data Visualization – Class Notes, 2024-25

18. What is not true about Data Visualization?


[AI, 2021, Term 1, 1 Mark]
a) Graphical representation of information and data
b) Data Visualization makes complex data more
accessible, understandable and usable.
c) Helps users in analyzing a large amount of data in a simpler
way.
d) No library needs to be imported to create charts in
Python language.
Ans. d)No library needs to be imported to create charts in Python
language.
19. Ms. Kalpana is working with an IT company, and she wants to
create charts from the data provided to her.
She generates the following graph : [AI, 2021, Term 1, 1 Mark]

a) plt.plot(x,y,marker=’#’, markersize=10, color=’red’,


linestyle=’dashdot’)
b) plt.plot(x,y,marker=’star’, markersize=10,
color=’red’)
c) plt.plot(x,y,marker=’@’, markersize=10,
color=’red’,linestyle=’dashdot’)
d) plt.plot(x,y,marker=’*’, markersize=10, color=’red’)
Ans. d) plt.plot(x,y,marker=’*’, markersize=10, color=’red’)

20. Write Python code to plot a bar chart for India‘s medal tally as
shown below: [SQP, 2022-23, 5 Mark]

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 23
Introduction to Data Visualization – Class Notes, 2024-25

Also give suitable python statement to save this chart.

Ans. import matplotlib.pyplot as plt


Category=['Gold','Silver','Bronze']
Medal=[20,15,18]
plt.bar(Category,Medal)
plt.ylabel('Medal')
plt.xlabel('Medal Type')
plt.title('Indian Medal tally in Olympics')
plt.show()
plt.savefig("aa.jpg")
21. Write a python program to plot a line chart based on the given
data to depict the changing weekly average temperature in Delhi
for four weeks.
Week=[1,2,3,4]
Avg_week_temp=[40,42,38,44] [SQP, 2022-23, 5 Mark]
Ans. import matplotlib.pyplot as plt
Week=[1,2,3,4]
Avg_week_temp=[40,42,38,44]
plt.plot(Week,Avg_week_temp)
plt.show()
22. Consider the following graph. Write the Python code to plot it. Also add
the Title, label for X and Y axis. [AI, 2023, 5 Mark]
Use the following data for plotting the graph
smarks=[10,40,30,60,55]
sname=["Sahil","Deepak","Anil","Ravi","Riti"]

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 24
Introduction to Data Visualization – Class Notes, 2024-25

Ans. import matplotlib.pyplot as plt


smarks=[10,40,30,60,55]
sname=["Sahil","Deepak","Anil","Ravi","Riti"]
plt.plot(sname,smarks)
plt.title("Marks secured by students in Term - 1")
plt.xlabel('Student Name')
plt.ylabel('Marks Scored')
plt.show()

23. Write Python code to draw the following bar graph representing the total
sales in each quarter. Add the Title, Label for X-axis and Y-axis.
Use the following data for plotting the graph: [AI, 2023, 5 Marks]
sales=[450,300,500,650]
qtr=["QTR1","QTR2","QTR3","QTR4"]

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 25
Introduction to Data Visualization – Class Notes, 2024-25

Ans. import matplotlib.pyplot as plt


#----------------------------#
sales=[450,300,500,650] # ignore as part
qtr=["QTR1","QTR2","QTR3","QTR4"]
#----------------------------#
plt.bar(qtr,sales)
plt.title("Sales each quarter")
plt.xlabel("Quarter")
plt.ylabel("Sales")
plt.show()
24 Assertion (A): In order to be able to use Python‘s data visualization
library, we need to import the pyplot module from matplot library.
Reason (R): The pyplot module houses a variety of functions required to
create and customize charts or graphs. [AI,Compt, 2023, 1 Mark]
(a) Both Assertion (A) and Reason (R) are true and Reason (R) is the
correct explanation of Assertion (A).
(b) Both Assertion (A) and Reason (R) are true, but Reason (R) is not the
correct explanation of Assertion (A).
(c) Assertion (A) is true, but Reason (R) is false.
(d) Assertion (A) is false, but Reason (R) is true.
Ans. (a) Both Assertion (A) and Reason (R) are true and Reason (R) is the
correct explanation of Assertion (A).
25. a) Consider the following graph. Write the Python code to plot it. Also add
the Title and Label for X and Y axis.
Use the following data to draw the graph. [AI,Compt, 2023, 5 Mark]
Class Marks
7 83
8 75
9 81
10 72
11 88
12 86

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 26
Introduction to Data Visualization – Class Notes, 2024-25

Ans. import matplotlib.pyplot as plt


cl = [7,8,9,10,11,12]
avmarks=[83,75,81,72,88,86]
plt.plot(cl,avmarks)
plt.title("AVERAGE RESULT OF CLASS VII-XII")
plt.xlabel('CLASS')
plt.ylabel('AVERAGE MARKS SCORED')
plt.show()
b) Write a Python code to draw the following bar graph representing the
average marks secured by each student in Term - 2 Exam. Add the Title
and Label for X-axis and Y-axis.
Use the following data to draw the graph: [AI,Compt, 2023, 5 Mark]
Names Average Marks
Ruby 84
Yugesh 92
Vishesh 45
Rakesh 72

Ans. import matplotlib.pyplot as plt


names = ['ruby','yugesh','Vishesh','Rakesh']
averagemarks=[84,92,45,72]
plt.bar(names,averagemarks)
plt.title("RESULT OF TERM-2 EXAM")
plt.xlabel('STUDENT NAMES')
plt.ylabel('AVERAGE MARKS SCORED')
plt.show()

26. a) The heights of 10 students of eighth grade are given below:


Height_cms=[145,141,142,142,143,144,141,140,143,144]
Write suitable Python code to generate a histogram based on the given
data, along with an appropriate chart title and both axis labels.
Also give suitable python statement to save this chart.
[SQP, 2023-24, 5 Mark]

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 27
Introduction to Data Visualization – Class Notes, 2024-25

Ans. import matplotlib.pyplot as plt #Statement 1


Height_cms=[145,141,142,142,143,143,141,140,143,144]
#Statement 2
plt.hist(Height_cms) #Statement 3
plt.title("Height Chart") #Statement 4
plt.xlabel("Height in cms") #Statement 5
plt.ylabel("Number of people") #Statement 6
plt.show() #Statement 7
plt.savefig("heights.jpg")

b) Write suitable Python code to create 'Favourite Hobby' Bar Chart as


shown below: [SQP, 2023-24, 5 Mark]

Also give suitable python statement to save this chart.


Ans. import matplotlib.pyplot as plt #Statement 1
hobby = ('Dance', 'Music', 'Painting', 'Playing Sports')
#Statement 2
users = [300,400,100,500] #Statement 3
plt.bar(hobby, users) #Statement 4
plt.title("Favourite Hobby") #Statement 5
plt.ylabel("Number of people") #Statement 6
plt.xlabel("Hobbies") #Statement 7
plt.show() #Statement 8
plt.savefig("hobbies.jpg")
27. The inventory management software of a grocery shop stores the price of
all fruits as follows: [AI, 2024, 5 Mark]
Fruits=['Apple','Guava','Papaya','Grapes','Mango']
Price=[l50,70,50,30,120]
Write suitable Python code to generate a Bar Chart on the given data.
Also add the chart title and label for X and Y axis. Also add suitable
statement to save this chart with the name fruits.png.
Ans. import matplotlib.pyplot as plt #Statement 1
Fruits=['Apple','Guava','Papaya','Grapes','Mango'] #Statement 2
Price=[150,70,50,30,120] #Statement 3
plt.bar(Fruits,Price) #Statement 4
plt.title("Fruits Prices") #Statement 5

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 28
Introduction to Data Visualization – Class Notes, 2024-25

plt.xlabel("Fruits") #Statement 6
plt.ylabel("Price") #Statement 7
plt.savefig("fruits.png") #Statement 8
plt.show() #Statement 9
28. Write suitable Python code to draw the following line chart "CO2 Emission"
having titleand label for X and Y axis as shown below.

Also give suitable Python statement to save this chart with the name,
emission.png [AI, 2024, 5 Mark]
Ans. import matplotlib.pyplot as plt #Statement 1
month=["April", "May", "June", "July", "August"] #Statement 2
percent=[40,50,30,60,20] #Statement 3
plt.plot(month, percent) #Statement 4
plt.title("Month wise CO2 emission") #Statement 5
plt.xlabel("Month") #Statement 6
plt.ylabel("Percentage") #Statement 7
plt.savefig("emission.png") #Statement 8
plt.show() #Statement 9

Prepared by : Mr. Taposh Karmakar, Air Force School Jorhat. Mobile – 7002070313. Last Updated : Wednesday, 26 Jun 2024 29

You might also like