What is Matplotlib?
Matplotlib is a powerful Python data visualization library used for creating static,
interactive, and animated plots.
It is widely used in data analysis, machine learning, and scientific computing.
Matplotlib is a low level graph plotting library in python that serves as a visualization
utility.
Matplotlib was created by John D. Hunter.
Matplotlib is open source and we can use it freely.
Matplotlib is mostly written in python, a few segments are written in C, Objective-C
and Javascript for Platform compatibility.
If you have Python and PIP already installed on a system, then installation of
Matplotlib is very easy.
Visualize data in various formats (bar, line, pie, scatter, histogram, etc.)
Install it using this command in CMD -> pip install matplotlib
Library Name: matplotlib
Main Module for Plotting: pyplot
Introduction
Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. It is
widely used for data visualization in scientific computing, data analysis, and machine learning. Matplotlib allows
users to generate plots, histograms, power spectra, bar charts, error charts, scatterplots, etc., with just a few lines of
code.
Key Features of Matplotlib
• Supports various plot types: line, bar, scatter, histogram, pie, etc.
• Highly customizable: control over colors, fonts, line styles, and markers.
• Supports both 2D and basic 3D plotting (via mpl_toolkits.mplot3d).
• Interactive mode for real-time data visualization.
• Integration with NumPy, Pandas, and other scientific libraries.
• Export plots to various formats such as PNG, PDF, SVG, and EPS.
Basic Example :
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.plot(x, y)
plt.title("Basic Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True)
plt.show()
In the above code:
1. We plot the data using plt.plot() with labels, colors, and line styles.
2. We add a title, axis labels, and a legend.
3. Finally, plt.show() displays the plot.
Types of Plots in Matplotlib
Plot Type Function Description
Line plot plt.plot(x, y) Basic plot to show trends
Bar chart plt.bar(categories, values) Shows comparisons using bars
Histogram plt.hist(data, bins=10) Shows frequency distribution
Scatter plot plt.scatter(x, y) Used to show correlation between variables
Pie chart plt.pie(sizes, labels=labels) Used to show parts of a whole
===============================================
import matplotlib.pyplot as plt
#plot-1
plt.subplot (2,3,1 )
x= [10, 20, 30 , 40]
plt. plot (x)
#plot-2
plt.subplot (2,3,6 )
y= [-10, -20, -30 , -40]
plt. plot (y)
plt.show()
====================================
import matplotlib.pyplot as plt
year = [1950, 1960, 1970, 1980, 1990, 2000, 2010, 2022, 2030]
Ind_population =[1.2 , 4.7, 7.3, 10.6, 13.67, 17.23, 19.56, 22.56, 25.67 ]
Chi_population =[1.8 , 5.2, 8.3, 12.6, 15.67, 18.23, 20.16, 22.16, 26.17 ]
plt. plot (year, Ind_population, color = 'blue', linestyle = "--", linewidth= 2, marker= "*", mfc = "green", mec =
"white", markersize = 10 )
plt. plot (year, Chi_population, color = 'red')
plt. title ("India vs China Population ")
plt. xlabel ("Year in each 10")
plt. ylabel ("Population in bil.")
plt. grid (axis = 'y', color = 'green')
plt. legend (["India" ,"China"])
plt.show ()
import matplotlib. pyplot as plt
sub_name = ['C','Cpp', 'Java', 'Py', 'PHP', 'SEng', 'DS']
Num_Student = [12, 9, 36, 27, 21, 2, 11]
c= ['red', 'green', 'blue', 'black', 'yellow', 'orange', 'pink']
#plt.bar (sub_name , Num_Student, width = 0.2 , color = c )
plt.barh (sub_name , Num_Student, height = .5, color = c )
plt. title("7th Aug Batch Status ")
plt. xlabel ("subject Name")
plt. ylabel ("Numbers of Student IN each subject ")
plt. grid (axis='y')
plt.show ()
import matplotlib.pyplot as plt
activity =['Reading', 'sleeping', 'work', 'Playing', 'Eating', 'Cooking', 'Mobile']
color = ['red', 'green', 'yellow','pink', '#ff1213', 'orange', '#ab1234']
myexplod= [0, 0.1, 0, 0, 0, 0, 0.2 ]
time =[4, 6, 5 ,2 , 1, 3 , 3 ]
plt.pie (time, labels= activity, shadow= True , startangle= 180, explode = myexplod , colors = color, autopct =
'%.3f%%')
plt. legend (['Reading', 'sleeping', 'work', 'Playing', 'Eating', 'Cooking', 'Mobile'])
plt.show ()
from random import *
#age = []
import matplotlib.pyplot as plt
'''
for i in range (1, 30+1 ):
age .append (randint (1, 100))
print (age)
'''
age = [73, 2, 11, 3, 1, 100, 26, 83, 92, 9, 25, 29, 74, 83, 24, 58, 68, 53, 81, 11, 81, 38, 69, 64, 8, 32, 39, 13, 4, 34]
plt. hist (age, bins = 10 , width= 5, color = 'blue', edgecolor = 'red' )
plt.show ()
from random import *
#age = []
import matplotlib.pyplot as plt
age = [73, 2, 11, 3, 1, 100, 26, 83, 92, 5]
l = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90 ]
plt. scatter (age, l )
plt.show ()
import matplotlib.pyplot as plt
#plot-1
plt.subplot (2,3,1 )
x= [10, 20, 30 , 40]
plt. plot (x)
#plot-2
plt.subplot (2,3,6 )
y= [-10, -20, -30 , -40]
plt. plot (y)
plt.show()
import csv
import matplotlib.pyplot as plt
Gender, Dept, Result =[], [],[]
obj = open ("Record.csv", 'r')
records = csv. reader (obj)
next (obj)
for record in records :
Gender.append (record[3])
Dept. append (record[2])
Result . append (record[4])
#plot 1
plt.subplot (2,2,1)
colors= ['red', 'green', 'blue']
plt. bar (['CSE', "Civil", 'ME'], [Dept.count ("CSE"),Dept.count ("CIVIL"),Dept.count ("ME")], width= 0.3, color =
colors )
plt.title ("Number of student in Each Dept")
plt. xlabel ("Dept Name")
plt. ylabel ("Number of Student")
#plot2
plt.subplot(2,2,2)
color = ['red', 'green']
plt. pie ([Gender.count ('M'), Gender.count ("F")], labels = ["Male", 'Female'], autopct = "%.2f%%", colors = color
)
plt. title ("% of Male & Female")
plt. legend (["Male", 'Female'])
#plot3
plt.subplot(2,2,4)
color = ['blue', 'green', 'yellow', 'red']
plt. pie ([Result.count ("1ST"),Result.count ("2ND"),Result.count ("3RD"),Result.count ("FAIL")], labels = ["1st",
'2nd','3rd','Fail'], autopct = "%.2f%%", colors = color, pctdistance = 1.7 )
plt. title ("Result Details")
plt. legend (["1st", '2nd','3rd','Fail'])
plt.show ()