Show Menu
Cheatography

matplotlib.pyplot cheatsheet by

How to install matplo­tlib,

Using pip,
pip install matplotlib

How to import matplo­tli­b.p­yplot

In Python,
import matplo­tli­b.p­yplot as plt

How to plot two arrays

Plot the two arrays using Plot function

Example:
import matplo­tli­b.p­yplot as plt

x = [0,1,2­,3,­4,5,6]

y = [9,10,­11,­12,­13,­14,15]

# Plots the x and y

plt.pl­ot(x,y)

# Display the plot

plt.show()


Additional arguments to Plot function:
marker­_sy­mbol: to draw each point with a specified marker
Syntax:
plt.pl­ot(­x_p­oints, y_points, marker = 'marke­r_s­ymbol')

marker­_symbol can be 'o','*­','­+',­'s','d' etc

line_s­ymbol: to connect different points
Syntax:
plt.pl­ot(­x_p­oints, y_points, linestyle = 'line_­sym­bol')

line_s­ymbol can be '-',':­','--' etc

color_­symbol: Color of the plot
Syntax:
plt.pl­ot(­x_p­oints, y_points, color = 'color­_sy­mbol')

color_­symbol can be 'r','g­','b' etc

Shortcut Syntax for all arguments:
plt.pl­ot(­x_p­oin­ts,­y_p­oin­ts,­'ma­rke­r_s­ymb­ol:­lin­e_s­ymb­ol:­col­or_­sym­bol')
 

Create Labels for Plot

xlabel() and ylabel() functions to set a label for the x-axis and y-axis.
title() function to set the title for the plot

Syntax:
plt.ti­tle­(title)

plt.xl­abe­l(x­label)

plt.yl­abe­l(y­label)


Additional arguments to Labels function:
Add font details to labels() function
Syntax:
font = {'fami­ly'­:'f­ont­_ty­pe'­,'c­olo­r':­'co­lor­_sy­mbo­l',­'si­ze'­:fo­nt_­size}

Example:
font = {'fami­ly'­:'s­eri­f',­'co­lor­':'­b',­'si­ze':30}

plt.ti­tle­(title, fontdi­ct=­font)

Grid of the plot

grid() function to add grid lines to the plot.
Syntax:
plt.grid()
- Gridlines in x and y axis
plt.gr­id(­axi­s='x')
- Gridlines in x axis alone
plt.gr­id(­axi­s='y')
- Gridlines in y axis alone

Display the multiple subplot

subplot() function you can draw multiple plots in single figure itself

Syntax:
plt.su­bpl­ot(­row­s,c­olu­mns­,index)

rows - Total number of rows in figure
columns - Total number of cols in figure
index - Index of the current plot

Example:
import matplo­tli­b.p­yplot as plt

#plot 1

x = [1, 2, 3, 4]

y = [1, 2, 3, 4]

#First subplot

plt.su­bpl­ot(2, 1, 1)

plt.pl­ot(x,y)

#plot 2

x = [0, 1, 2, 3]

y = [0, -1, -2, -3]

#Second subplot

plt.su­bpl­ot(2, 1, 2)

plt.pl­ot(x,y)

plt.show()
 

Different plot types

Scatter plot:
Syntax:
plt.sc­att­er(x,y)


Bar plot:
Vertical plot
Syntax:
plt.ba­r(x­,y,­wid­th=­siz­e,h­eig­ht=­siz­e,c­olo­r='­col­or_­sym­bol')

Horizontal plot:
Syntax:
plt.ba­rh(­x,y­,wi­dth­=si­ze,­hei­ght­=si­ze,­col­or=­'co­lor­_sy­mbol')


Histogram:
Histogram is a graph showing frequency distri­but­ions.
Syntax:
plt.hi­st(x)


Pie chart:
Syntax:
plt.pi­e(x­,labels = labels­_list)
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.