Matplot Library

Naman Mehra
3 min readJun 14, 2021

Matplot library is a plotting library for python. It is basically used for plotting 3D or 2D graphs. Matplot library allows us to create some greatly looking graphs from our data.

Importing and Installing Matplotlib

pip install matplotlib
from matplotlib import pyplot as plt
%matplotlib inline

Simple plotting a graph

x = list(range(0,10))
y = list(range(-10,0))
plt.plot(x,y)

If you want to look at a particular section of the graph

a = [0,10,1,2,9,6]
b = [1,4,3,8,9,3]
plt.plot(a,b)
plt.axis([1,9,3,9]) #plt.axis([x-axis start,x-axis end , y-axis start, y-axis end])
plt.title('Polygon')
plt.xlabel('X-axis')
plt.ylabel('Y-label')
plt.plot(a,b)

We can also use xticks or yticks to change the values on x or y-axis.

a = [0,10,1,2,9,6]
b = [1,4,3,8,9,3]
plt.xticks((0,2,4,6,8,10),('N','A','M','A','N','M'))
plt.plot(a,b)
x = [1,2,3]
y = [2,4,6]
x2 = [5,7,8]
y2 = [10,14,16]
plt.plot(x,y,label = 'Line1',linewidth=3)
plt.plot(x2,y2,label = 'Line2',linewidth = 4)
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True,color='k')

Plotting Bar Graphs

plt.bar([1,3,5,7,9],[2,4,6,8,10],label='Bar1')
plt.bar([2,4,6,8,10],[1,3,5,7,9],label='Bar2')
plt.legend()
plt.xlabel('Bar No.')
plt.ylabel('Bar Ht.')
plt.title('Bar Graph')

Plotting Histogram

import random
population_ages=random.sample(range(0,100),30)
bins = [0,10,20,30,40,50,60,70,80,90,100]
plt.hist(population_ages, bins, histtype='bar', rwidth=0.7)
plt.xlabel('x')
plt.ylabel('y')

Plotting Scatter plot

x = random.sample(range(0,100),50)
y = random.sample(range(0,100),50)
plt.scatter(x,y,label='Scatter Plot',color='r')
plt.xlabel('X')
plt.ylabel('Y')

Stack plot

days=[1,2,3,4,5]
a = random.sample(range(0,10),5)
b = random.sample(range(0,10),5)
c = random.sample(range(0,10),5)
d = random.sample(range(0,10),5)
print(a)
print(b)
print(c)
print(d)
plt.plot([],[],color='r',label='a') #lines are drawn to give labels as we can't give labels in plt.stackplot
plt.plot([],[],color='g',label='b')
plt.plot([],[],color='b',label='c')
plt.plot([],[],color='k',label='d')
plt.stackplot(days,a,b,c,d,colors = ['r','g','b','k'])
plt.legend()

Pie plot

slices = [10,15,20,30]
x = ['a','b','c','d']
colorss = ['r','g','b','y']
plt.pie(slices,
labels = x,
startangle = 0,
shadow =True,
explode = [0,0,0.1,0], #will make the respective slice protrude
autopct = '%1.1f%%' #will show the percentages on the pieplot
)
plt.title('PiePlot')

Thank you for reading this far.
Follow me on linkedin.

Reference :https://www.youtube.com/redirect?event=video_description&redir_token=QUFFLUhqa0RTUXNCQWpyRm1wckl0SGJiZTZHMkpoT1k1UXxBQ3Jtc0ttVm5YVGEyVnRrYWV2YXRHWndFM0czcFB2OE4zTnVGcmRWOERHZzB2S0xncUlES2taT0lCTWdVNUNnbjZPc2t2X2l1R2JDVFJsM28yYWYtOHdLMHU1d1Q2WTJTQkNfdXpPdDlGaXRrQm1iRzlNcElQUQ&q=https%3A%2F%2Fwww.edureka.co%2Fdata-science-python-certification-course

--

--