What is Matplotlib?
Matplotlib is a Python library used for data visualization.
It helps us to create graphs such as line, Scatter, Bar, Histogram, pie etc.
Example:
Data:
Year Sales
2020 100
2021 150
2022 200
We can show them in a graph, which is easier to understand.
Installing Matplotlib
pip install matplotlib
Import library
import [Link] as plt
pyplot is the module used to create graphs.
First Simple Plot
program:
import [Link] as plt
x = [1,2,3,4]
y = [10,20,25,30]
[Link](x,y)
[Link]()
Explain:
Part Meaning
x x-axis values
Part Meaning
y y-axis values
plot() create graph
show() display graph
Graph shows a line chart.
Adding Title and Labels
Graphs should always have labels.
import [Link] as plt
x = [1,2,3,4]
y = [10,20,25,30]
[Link](x,y)
[Link]("Sales Graph")
[Link]("Year")
[Link]("Sales")
[Link]()
Explain:
Function Purpose
title() graph title
xlabel() x-axis label
ylabel() y-axis label
Adding Grid
Grid helps to read values clearly.
[Link]()
Example:
[Link](x,y)
[Link]()
[Link]()
Changing Line Style
Students can customize the graph.
Example:
[Link](x,y, linestyle="--")
Other styles:
Style Meaning
"-" solid
"--" dashed
":" dotted
Changing Marker
Markers show each data point.
[Link](x,y, marker="o")
Example markers:
Marker Shape
o circle
s square
^ triangle
* star
Multiple Lines in One Graph
Example:
x = [1,2,3,4]
y1 = [10,20,30,40]
x2 = [3,5,7,9]
y2 = [5,15,25,35]
[Link](x,y1)
[Link](x,y2)
[Link]()
This shows two lines in one graph.
Legend
Legend tells which line represents which data.
[Link](x,y1,label="Product A")
[Link](x,y2,label="Product B")
[Link]()
[Link]()
Bar Chart
Bar charts are used for comparison.
Example:
import [Link] as plt
students = ["A","B","C","D"]
marks = [80,70,90,60]
[Link](students,marks)
[Link]()
Graph shows marks of students.
Horizontal Bar Chart
[Link](students,marks)
Pie Chart
Used to show percentage distribution.
Example:
import [Link] as plt
data = [40,30,20,10]
labels = ["Python","Java","C","C++"]
[Link](data, labels=labels)
[Link]()
Histogram
Histogram shows data distribution.
Example:
import [Link] as plt
marks = [50,60,70,80,90,60,70,80]
[Link](marks)
[Link]()
Useful for:
exam marks
age distribution
income distribution
Scatter Plot
Used to show relationship between two variables.
Example:
import [Link] as plt
x = [1,2,3,4,5]
y = [2,4,5,4,5]
[Link](x,y)
[Link]()
Example use:
study hours vs marks
height vs weight
Subplots (Multiple Graphs)
Example:
import [Link] as plt
x = [1,2,3]
y1 = [2,4,6]
y2 = [1,3,5]
[Link](1,2,1)
[Link](x,y1)
[Link](1,2,2)
[Link](x,y2)
[Link]()
Meaning:
Parameter Meaning
1 rows
2 columns
1/2 graph number
Saving Graph
Students can save graphs as image.
[Link]("[Link]")