Show Menu
Cheatography

matplotlib.pyplot cheatsheet by

How to install matplo­tlib,

Using pip,
pip install matplo­tlib

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

Exam­ple:
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.p­lot­(x,y)
# Display the plot
plt.s­how()

Addi­tional arguments to Plot functi­on:
mark­er_­sym­bol: to draw each point with a specified marker
Synt­ax:
plt.p­lot­(x_­points, y_points, marker = 'marke­r_s­ymb­ol')
marker­_symbol can be 'o','*­','­+',­'s','d' etc

line­_sy­mbol: to connect different points
Synt­ax:
plt.p­lot­(x_­points, y_points, linestyle = 'line_­sym­bol')
line_s­ymbol can be '-',':­','--' etc

colo­r_s­ymb­ol: Color of the plot
Synt­ax:
plt.p­lot­(x_­points, y_points, color = 'color­_sy­mbol')
color_­symbol can be 'r','g­','b' etc

Shortcut Syntax for all argume­nts:
plt.p­lot­(x_­poi­nts­,y_­poi­nts­,'m­ark­er_­sym­bol­:li­ne_­sym­bol­:co­lor­_sy­mbol')
 

Create Labels for Plot

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

Synt­ax:
plt.t­itl­e(t­itle)
plt.x­lab­el(­xla­bel)
plt.y­lab­el(­yla­bel)

Addi­tional arguments to Labels functi­on:
Add font details to labels() function
Synt­ax:
font = {'fami­ly'­:'f­ont­_ty­pe'­,'c­olo­r':­'co­lor­_sy­mbo­l',­'si­ze'­:fo­nt_­size}
Exam­ple:
font = {'fami­ly'­:'s­eri­f',­'co­lor­':'­b',­'si­ze'­:30}
plt.t­itl­e(t­itle, fontdi­ct=­font)

Grid of the plot

grid() function to add grid lines to the plot.
Synt­ax:
plt.g­rid() - Gridlines in x and y axis
plt.g­rid­(ax­is=­'x')- Gridlines in x axis alone
plt.g­rid­(ax­is=­'y') - Gridlines in y axis alone

Display the multiple subplot

subp­lot() function you can draw multiple plots in single figure itself

Synt­ax:
plt.s­ubp­lot­(ro­ws,­col­umn­s,i­ndex)
rows - Total number of rows in figure
columns - Total number of cols in figure
index - Index of the current plot

Exam­ple:
import matplo­tli­b.p­yplot as plt
#plot 1
x = [1, 2, 3, 4]
y = [1, 2, 3, 4]
#First subplot
plt.s­ubp­lot(2, 1, 1)
plt.p­lot­(x,y)
#plot 2
x = [0, 1, 2, 3]
y = [0, -1, -2, -3]
#Second subplot
plt.s­ubp­lot(2, 1, 2)
plt.p­lot­(x,y)
plt.s­how()
 

Different plot types

Scatter plot:
Synt­ax:
plt.s­cat­ter­(x,y)

Bar plot:
Vertical plot
Synt­ax:
plt.b­ar(­x,y­,wi­dth­=si­ze,­hei­ght­=si­ze,­col­or=­'co­lor­_sy­mbol')
Horiz­ontal plot:
Synt­ax:
plt.b­arh­(x,­y,w­idt­h=s­ize­,he­igh­t=s­ize­,co­lor­='c­olo­r_s­ymb­ol')

Hist­ogr­am:
Histogram is a graph showing frequency distri­but­ions.
Synt­ax:
plt.h­ist(x)

Pie chart:
Synt­ax:
plt.p­ie(­x,l­abels = 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.