0% found this document useful (0 votes)
7 views50 pages

Chapter 2 - part 1 - Line charts & Bar charts

The document provides an overview of data visualization using the Matplotlib library in Python, specifically focusing on the pyplot module for creating 2D plots. It covers installation, components of a plot, types of charts, and detailed instructions on how to create line charts, including customization options for markers, lines, and subplots. Additionally, it includes examples and homework questions related to the concepts discussed.

Uploaded by

Reshmi Manoj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views50 pages

Chapter 2 - part 1 - Line charts & Bar charts

The document provides an overview of data visualization using the Matplotlib library in Python, specifically focusing on the pyplot module for creating 2D plots. It covers installation, components of a plot, types of charts, and detailed instructions on how to create line charts, including customization options for markers, lines, and subplots. Additionally, it includes examples and homework questions related to the concepts discussed.

Uploaded by

Reshmi Manoj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

7/10/2024

DATA VISUALIZATION USING


PYPLOT

Data Visualization
 Data visualization is the presentation of data in a pictorial or
graphical format.

 By using visual elements like charts, graphs and maps, data


visualization tools provide an accessible way to see and
understand trends and patterns in data.

 It enables decision makers to see analytics presented visually,


so that, they can grasp difficult concepts or identify new
patterns.

 Data visualization in python can be done using exclusive


libraries. Eg. Matplotlib , Seaborn

1
7/10/2024

Matplotlib
 Matplotlib is a most popular, high quality, 2D plotting
library for the Python programming language and its
numerical mathematics extension is NumPy.

 It provides many interfaces and functions to create 2D


graphs and plots in Python.

 Matplotlib library offers many different collections of sub


modules. Pyplot is one such sub module.

Installing Matplotlib

 To install matplotlib:
pip install matplotlib

2
7/10/2024

What is pyplot ?
 pyplot is a collection of methods within the matplot
library (of python) which allows user to construct 2D
plots easily and interactively.

 plot() from pyplot will create figures and axes


automatically.

 It makes some changes to a figure, creating plotting


area in a figure, decorating the plot with labels,
plotting some lines in a plotting area.

Import pyplot
 To make use of pyplot methods, you need to
import it by issuing following command:

import matplotlib.pyplot

or

import matplotlib.pyplot as py

3
7/10/2024

Components (nomenclature) of a plot


 Figure: It is a canvas which contains plots. A figure can contain many
axes
 Áxes: It is the plot itself. Axes contains 2 or 3 axis objects
 Axis: x-axis & y-axis. These are number lines that takes care of
generating the graph limits.
 Ártist : Every object on the figure is called as artist
 Labels: X label, Y label are axis labels, which allows us to specify what
kind of data we are plotting
 Title : Title of the graph describes what it is
 Legend: Explains the purpose of each line or colour in the figure.
 xticks ( [ ticks, labels]): Sets the current tick locations and labels of X-axis
 yticks ( [ ticks, labels]): Sets the current tick locations and labels of Y-axis
 Ticks are the values used to show specific points on the coordinate axis.

Components (nomenclature) of a plot

4
7/10/2024

TYPES OF CHARTS

1 4
LINE CHART HISTOGRAM
2 5
BAR CHART BOX CHART
3 6
PIE CHART SCATTER PLOT

1. Line Chart
 A Line Graph or Chart is a simple
graph that shows the result in the
form of lines.
 It displays information as a series
of data points called markers
connected by straight lines
 It represents trends over a time.
 Line chart can be created using
the plot() function in the pyplot
module.

5
7/10/2024

Markers and Lines


 All the plots are made up of points [ i.e., (x,y) pairs ]
with lines joining them.
 Points are the real generators of the plot because
points mark position.
 So they are called markers in matplotlib terminology.
 A single dot is the default marker.
 Lines are used to join the markers.
 Lines are by default, straight thin segments, blue in
colour.

plot() function
 It is a function in the pyplot module.
 Used to create line charts.
 Syntax:
plt.plot ( x, y, color, marker type, line width, linestyle,
marker, marker size,
marker edge color)
 x is the data on the horizontal axis (X-axis)
 y is the data on the vertical axis (Y-axis)
 Remaining parameters help us to change the marker style
and the line style.

6
7/10/2024

Steps to Draw a Line Chart


1. Import matplotlib
2. Define X-axis values as a list
3. Accept Y-axis values as a list
4. Plot them on canvas using .plot() function.
5. Give a name to x-axis and y-axis
using .xlabel() and .ylabel() functions.
6. Give a title to your plot using .title() function.
7. Finally, to view your plot, we
use .show() function.
8. Display the chart using show()

Program to draw a simple line chart

7
7/10/2024

Program to draw a simple line chart

Interactive Navigation Toolbar


 An interactive ‘navigation tool bar with buttons for functions located at the
bottom of the figure is available by default in every figure’.

Reset original window


Back to previous view from the current view

Forward to next view from the current view

Pan axis with left button /Zoom any section in the plotted figure with right button

Zoom to a rectangle, which we draw on the figure


Configure subplots (pop up window - space around the subplots can be adjusted)

Save the figure to the hard disk (Save as dialog box pops up)

8
7/10/2024

Functions associated with


line chart
 plt.xlabel() – to give a label for X-axis
 plt.ylabel() – to give a label for Y-axis
 plt.title() – to give a title for the plot
 plt.grid(True) – to add grid lines to the plot
 plt.subplot() – to place multiple plots on a single figure
 plt.legend() – to place the legend on the axes. Legend is
a text or a string that is used to understand the graph.
 plt.show() – to display the figure

Setting Labels of X,Y Axis and Title of a Line Chart

9
7/10/2024

Showing grid lines

Parameters of plot() for changing


the line style
Line width
Line style
Color

10
7/10/2024

Values of linestyle
linestyle Abbreviation Eg:
p.plot(x, y, linestyle = ‘solid‘ ) or
solid - p.plot(x, y, linestyle = '-‘ )

p.plot(x, y, linestyle = ‘dashed‘ ) or


dashed -- p.plot(x, y, linestyle = '--‘ )

p.plot(x, y, linestyle = ‘dashdot‘ ) or


dashdot -. p.plot(x, y, linestyle = '-.‘ )

p.plot(x, y, linestyle = ‘dotted‘ ) or


dotted : p.plot(x, y, linestyle = ‘:‘ )

 Linestyle is a parameter of plot() function


 Default value of linestyle is ‘solid’

Values of color
Color Code Color Code
Red ‘r’ Green ‘g’
Blue ‘b’ Yellow ‘y’
Megenta ‘m’ Cyan ‘c’
Black ‘k’ White ‘w’

 color is a parameter of plot() function to which a color or it’s code can be assigned and
colour of the line changes.
 Eg: p.plot (x, y, color = ‘m’) or
p.plot (x, y, color='magenta‘)
 Default value of color is ‘b’ or ‘blue’

11
7/10/2024

Value of linewidth
 Line thickness increases according to the value of the
linewidth
 You can change the line width as,
linewidth = <width> in points
 Width should be a positive integer , i.e., a number >0
 No line is displayed if width is zero.

Changing colour, width and style of line

12
7/10/2024

Multiple Plots: Plotting multiple lines in one chart


label parameter of plot() function
allows us to assign a name to the
line, which we can later show in
the legend

Multiple plots of different styles

13
7/10/2024

Multiple views: subplot() & subplots_adjust()


 To plot graph in multiple views , use subplot() function
Syntax :
 plt.subplot (number of rows,
number of columns,
figure number)

• subplots_adjust() is used for providing height-wise space (hspace) and


width-wise space (wspace) between two sub plots.
• So their titles and other components don't overlap or collide with each
other.

Example: subplot()
Here, subplot() function divides the
figure in such a way that there are 2
rows and 1 column. Chart 1 is placed
in the 1st subplot and Chart 2 in the
2nd subplot. There is no space
between the 2 subplots.

14
7/10/2024

Example: subplots_adjust()
Here, hspace parameter of
subplots_adjust() function is the
amount of height reserved for space
between two subplots

Example: subplot()
Here, subplot() function divides the
figure in such a way that there are 2
columns and 1 row. Chart 1 is placed
in the 1st subplot and Chart 2 in the
2nd subplot. There is no space
between the 2 subplots

15
7/10/2024

Example: subplots_adjust()
Here, wspace parameter of
subplots_adjust() function is the
amount of width reserved for space
between the two subplots

Example: arange()
• arange() function of numpy library
is a tool for creating numeric
sequences in python.
Syntax:
np.arange(start, stop, step)

16
7/10/2024

Parameters of plot() for changing the


marker style
 The default marker is a dot.
 To change the marker style, use the following parameters
 marker : Type of marker used (Specify a marker code)
 markersize : Number corresponding to the size of the marker
 markeredgecolor : Outline colour
 markerfacecolor : Fill colour
 markeredgewidth : Thickness of outline

Values of the parameter - marker

17
7/10/2024

Example: Changing the marker style

Program to plot an algebraic expression 10x+14


using line chart and change the marker style

18
7/10/2024

Program to plot the function y=x2

Program to plot sine wave (y=sin(x)) using line chart

19
7/10/2024

Program to plot a line chart y2=4x

Write a program to draw a line chart to show the population of


India vs Pakistan from1960 – 2010
Ind = [449.48, 553.57, 696.783, 870.133,1000.4, 1309.1]
Pak = [44.91, 58.06, 78.07, 107.7, 138.5, 170.6]

20
7/10/2024

Program to draw a line chart to show the population of India vs Pakistan from1960 – 2010

Solved Question No. 39


Write a program to plot the chart as given below

21
7/10/2024

Q. 39 :: ANSWER

Solved Question No. 40


Write a program to plot the chart as given below

22
7/10/2024

Q. 40 :: ANSWER

Write a program to plot a quadratic equation (eg: 𝑦=1−(𝑥2)/2 )


using dashed line chart.

23
7/10/2024

Write a program to plot multiple lines with different colors

 X value is an optional parameter of plot()


 Default value of X is 0,1,2,3,…
 Y values generates are 1,2,3,4
 For the yellow line, (x,y) points plotted
are: (0,1), (1,2), (2,3), (3,4)

Write a program to plot multiple lines of different styles using a


single plot() function

 In a single plot() function, 3 sets of


values are given.

24
7/10/2024

SETTING TICKS FOR AXES - xticks() and yticks()

 Ticks are used to show specific points on the


coordinate axis
 xticks() – used to set the tick locations and their
labels of X axis
 yticks() – used to set the tick locations and their
labels of Y axis

SETTING X AND Y LIMITS – xlim() and ylim()

 You can set the axes limits using the


following functions:-
1. xlim() function – to set the limits for
X axis
2. ylim() function – to set the limits for
Y axis

25
7/10/2024

Write a program to plot the chart as given below

ANSWER

26
7/10/2024

Write a program to plot the chart as given below

ANSWER

27
7/10/2024

Solved Question No. 34


Write a program to plot a chart as given below.

Q. 34 :: ANSWER

OR

# Default value of x is [0,1,2,..]

28
7/10/2024

Solved Question No. 8


Write a program to plot the speed of passenger train as shown in
the figure given below: Assume the values of x from 1 to 5 and the
other axis is taken as 1.5x, 3.0x and x/3.0.

Q. 8 :: ANSWER

OR

29
7/10/2024

Solved Question No. 35


Write a program to plot a chart as given below.

Q. 35 :: ANSWER

30
7/10/2024

Solved Question No. 37

Write a program to draw a line with suitable label in the X-axis and
Y-axis, and a title.

Q. 37 :: ANSWER

OR

31
7/10/2024

Solved Question No. 38

Write a program to draw a line with suitable label in the X-axis and
Y-axis, and a title.

Q. 38 :: ANSWER

32
7/10/2024

Unsolved Question No. 1

Q. 1 :: ANSWER

33
7/10/2024

HW :PG 3.64
QN:2 to 5

2.What is matplotlib?
3. What do you mean by pip?
4. How do we update pip?
5. Why do we update pip?

Homework
Answers

34
7/10/2024

2. Matplotlib is a most popular, high quality, 2D plotting library for


the Python programming language and its numerical mathematics extension is
NumPy.

3. pip is the standard package manager for Python. It allows you to install and
manage additional packages that are not part of the Python standard library.

4. To upgrade PIP in Windows, you need to open the Windows Command


Prompt, and type/copy the command below:

>>> python –m pip install –upgrade pip

5. if you’re using an old version of pip, installing the latest version of a Python
package might fail—or install in a slower, more complex way.

When to use line graph?

• Line graphs are drawn to represent the independent data


on the horizontal x-axis (e.g. time) and the dependent
data on the vertical y-axis.
• Line graphs are used to track changes over short and
long periods of time.
• Line graphs can also be used to compare changes over
the same period of time for more than one group.

35
7/10/2024

Pros and Cons of Using Line Graphs

Pros
• Work well in showing trends chronologically.
• Clearly display relationships with continuous periodical data.
• Visualize data changes at a glance.
Cons
• Matches best with periodical data.
• Mess the chart if many categories are compared in one line chart.

2. BAR CHART

36
7/10/2024

2. BAR CHART
 A bar chart is a 2D data visualization made up of
rectangular bars each for a specific category with its
length representing the value of that category.
 Hence, bar chart or bar graph is a chart or graph that
presents categorical data with rectangular bars.
 The heights / lengths of bars are proportional to the values
that they represent.
 It is useful to compare a given numeric value on different
categories.

2. BAR CHART
 It can also be used with 2 data series.
 The bars can be plotted vertically or horizontally.
 We can configure the width, alignment, color, ticks, limits
and label of the chart.
 X-axis will be a range with the same quantity as that of the
items.
For e.g.: If there are 4 items, there will be 4 bars and
hence X-axis will be a range of 4 values].

37
7/10/2024

bar() function : used to plot a


vertical bar chart

To plot the population of cities


using bar graph

38
7/10/2024

Changing Color And Width of Bar

Arguments of bar function are:


• width to change the width of bars
• color to change the colour of bars

Applying different colours, but same width

39
7/10/2024

Applying different widths, but same


colour

Practical implementation (Pg. 3.25)


Plot a simple bar chart with orange color and width 0.5

40
7/10/2024

Practical implementation 19 (Pg. 3.27)


Plot a simple bar chart showing favourite type of movie of
different sets of people

Plot a simple bar chart showing the usage of various


programming languages

41
7/10/2024

Multiple bar charts – Example


(Pg. 3.26)

Multiple bar charts - Example

42
7/10/2024

barh() function : used to plot a


horizontal bar chart

To plot the population of cities using horizontal bar graph

Arguments of barh() are:


• height to change the breadth of bars
• color to change the colour of bars

43
7/10/2024

Plot a horizontal bar chart showing the usage of various


programming languages

Multiple horizontal bar charts - Example

44
7/10/2024

Write a program to plot the following chart to depict the


popularity of various programming language.

To plot a bar chart to depict the popularity of various


programming languages.

45
7/10/2024

Write a program to create a bar plot of scores by group and gender.


Use multiple X values on the same chart for men and women.
Sample data: Means (men) = (22,30,35,35,26)
Means (women) = (25,32,30,35,29)

46
7/10/2024

Home Work

Pg. 3.48 Solved Qns. 6,9,10


Pg. 3.64 Unsolved Qns. 14,15

Home Work Answers

Pg. 3.64 Unsolved Qns. 14,15

47
7/10/2024

PROGRAM :14 Display a bar chart of the number of students in a class.


Data: Class: I,II,III,IV,V,VI,VII,VIII,IX,X
Strengths:40,43,45,47,49,38,50,37,43,39
Use different colours for each bar

48
7/10/2024

PROGRAM :15 Display a horizontal bar chart of the number of


students in a class.
Data: Class: I,II,III,IV,V,VI,VII,VIII,IX,X
Strengths:40,43,45,47,49,38,50,37,43,39
Use different colors for each bar

49
7/10/2024

WHEN TO USE BAR GRAPH?

• Bar graphs are used to display data in a similar way to


line graphs.
• Rather than using a point on a plane to define a value, a bar
graph uses a horizontal or vertical rectangular bar that levels off
at the appropriate level.
• If you have comparative data that you would like to represent
through a chart then a bar chart would be the best option.
• This type of chart is one of the more familiar options as it is
easy to interpret.

SAVING FIGURE

• If you want to save the plotted figure use the


following statement

matplotlib.pyplot.savefig(“filenamewithpath”)
For example:
plt.savefig(“pchart.png”)
• Or you can click the save button on the GUI panel
• The file will be saved in the python folder.

50

You might also like