You are on page 1of 17

1.

Write programs to understand the use of Matplotlib for Simple Interactive Chart, Set the Properties
of the Plot, matplotlib and NumPy.

Matplotlib

Matplotlib is one of the most popular Python packages used for


data visualization. It is a cross-platform library for making 2D plots
from data in arrays. It provides an object-oriented API that helps
in embedding plots in applications using Python GUI toolkits such
as PyQt, WxPythonotTkinter. It can be used in Python and
IPython shells, Jupyter notebook and web application servers
also.
Matplotlib is written in Python and makes use of NumPy, the
numerical mathematics extension of Python.
Matplotlib has a procedural interface named the Pylab, which is
designed to resemble MATLAB, a proprietary programming
language developed by MathWorks. Matplotlib along with NumPy
can be considered as the open source equivalent of MATLAB.
Matplotlib was originally written by John D. Hunter in 2003. 
Matplotlib - Environment Setup
Matplotlib and its dependency packages are available in the form
of wheel packages on the standard Python package repositories
and can be installed on Windows, Linux as well as MacOS
systems using the pip package manager.
pip3 install matplotlib

Matplotlib - Anaconda distribution


Anaconda is a free and open source distribution of the Python
and R programming languages for large-scale data processing,
predictive analytics, and scientific computing. The distribution
makes package management and deployment simple and easy.
Matplotlib and lots of other useful (data) science tools form part of
the distribution. Package versions are managed by the package
management system Conda. The advantage of Anaconda is that
you have access to over 720 packages that can easily be
installed with Anaconda's Conda, a package, dependency, and
environment manager.
Matplotlib - Jupyter Notebook
Jupyter is a loose acronym meaning Julia, Python, and R. These
programming languages were the first target languages of the
Jupyter application, but nowadays, the notebook technology also
supports many other languages.
To start the Jupyter notebook, open Anaconda navigator. Launch
Jupyter Notebook from the Navigator . You will see the application
opening in the web browser on the following address
− http://localhost:8888.
Matplotlib - Pyplot API
A new untitled notebook with the .ipynbextension (stands for the
IPython notebook) is displayed in the new tab of the browser.
matplotlib.pyplot is a collection of command style functions that
make Matplotlib work like MATLAB. Each Pyplot function makes
some change to a figure. For example, a function creates a figure,
a plotting area in a figure, plots some lines in a plotting area,
decorates the plot with labels, etc
Matplotlib - Simple Plot
We shall now display a simple line plot of angle in radians vs. its
sine value in Matplotlib. To begin with, the Pyplot module from
Matplotlib package is imported, with an alias plt as a matter of
convention.
import matplotlib.pyplot as plt
Next we need an array of numbers to plot. Various array
functions are defined in the NumPy library which is imported with
the np alias.
import numpy as np
We now obtain the ndarray object of angles between 0 and 2π
using the arange() function from the NumPy library.
x = np.arange(0, math.pi*2, 0.05)
The ndarray object serves as values on x axis of the graph. The
corresponding sine values of angles in x to be displayed on y
axis are obtained by the following statement −
y = np.sin(x)
The values from two arrays are plotted using the plot() function.
plt.plot(x,y)
You can set the plot title, and labels for x and y axes.
You can set the plot title, and labels for x and
y axes.
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')
The Plot viewer window is invoked by the show() function −
plt.show()
The complete program is as follows −
from matplotlib import pyplot as plt
import numpy as np
import math #needed for definition of pi
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)
plt.plot(x,y)
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')
plt.show()

 Define the x-axis and corresponding y-axis values as lists.


 Plot them on canvas using .plot() function.
 Give a name to x-axis and y-axis
using .xlabel() and .ylabel() functions.
 Give a title to your plot using .title() function.
 Finally, to view your plot, we use .show() function.
Creating a Simple Plot
# importing the required module 
import matplotlib.pyplot as plt 
    
# x axis values 
x = [1,2,3] 
# corresponding y axis values 
y = [2,4,1] 
    
# plotting the points  
plt.plot(x, y) 
    
# naming the x axis 
plt.xlabel('x - axis') 
# naming the y axis 
plt.ylabel('y - axis') 
    
# giving a title to my graph 
plt.title('My first graph!') 
    
# function to show the plot 
plt.show() 
The code seems self-explanatory. Following steps were followed:
 Define the x-axis and corresponding y-axis values as lists.
 Plot them on canvas using .plot() function.
 Give a name to x-axis and y-axis using .xlabel() and .ylabel() functions.
 Give a title to your plot using .title() function.
 Finally, to view your plot, we use .show() function.

Let’s have a look at some of the basic functions that are often used in
matplotlib.
Method Description

it creates the plot at


the background of
computer, it doesn’t
displays it. We can
also add a label as
it’s argument that by
what name we will
call this plot – utilized
plot() in legend()

it displays the created


show() plots

xlabel() it labels the x-axis

ylabel() it labels the y-axis

it gives the title to the


title() graph

it helps to get access


over the all the four
gca() axes of the graph

gca().spines[‘right/left/top/bottom’].set_visible(True/ it access the


False) individual spines or
Method Description

the individual
boundaries and helps
to change theoir
visibility

it decides how the


markings are to be
xticks() made on the x-axis

it decides how the


markings are to be
yticks() made on the y-axis

pass a list as it’s


arguments of all the
plots made, if labels
are not explicitly
specified then add the
values in the list in
the same order as the
gca().legend() plots are made

it is use to write
comments on the
graph at the specified
annotate() position

whenever we want
the result to be
displayed in a
separate window we
use this command,
and figsize argument
decides what will be
the initial size of the
window that will be
displayed after the
figure(figsize = (x, y)) run
Method Description

it is used to create
multiple plots in the
same figure with r
signifies the no of
rows in the figure, c
signifies no of
columns in a figure
and i specifies the
positioning of the
subplot(r, c, i) particular plot

it is used to set the


range and the step
size of the markings
on x – axis in a
set_xticks subplot

it is used to set the


range and the step
size of the markings
on y – axis in a
set_yticks subplot

import matplotlib.pyplot as plt


  
  
a = [1, 2, 3, 4, 5]
b = [0, 0.6, 0.2, 15, 10, 8, 16, 21]
plt.plot(a)
  
# o is for circles and r is 
# for red
plt.plot(b, "or")
  
plt.plot(list(range(0, 22, 3)))
  
# naming the x-axis
plt.xlabel('Day ->')
  
# naming the y-axis
plt.ylabel('Temp ->')
  
c = [4, 2, 6, 8, 3, 20, 13, 15]
plt.plot(c, label = '4th Rep')
  
# get current axes command
ax = plt.gca()
  
# get command over the individual
# boundary line of the graph body
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
  
# set the range or the bounds of 
# the left boundary line to fixed range
ax.spines['left'].set_bounds(-3, 40)
  
# set the interval by  which 
# the x-axis set the marks
plt.xticks(list(range(-3, 10)))
  
# set the intervals by which y-axis
# set the marks
plt.yticks(list(range(-3, 20, 3)))
  
# legend denotes that what color 
# signifies what
ax.legend(['1st Rep', '2nd Rep', '3rd Rep', '4th Rep'])
  
# annotate command helps to write
# ON THE GRAPH any text xy denotes 
# the position on the graph
plt.annotate('Temperature V / s Days', xy = (1.01, -2.15))
  
# gives a title to the Graph
plt.title('All Features Discussed')
  
plt.show()
import matplotlib.pyplot as plt
  
  
a = [1, 2, 3, 4, 5]
b = [0, 0.6, 0.2, 15, 10, 8, 16, 21]
c = [4, 2, 6, 8, 3, 20, 13, 15]
  
# use fig whenever u want the 
# output in a new window also 
# specify the window size you
# want ans to be displayed
fig = plt.figure(figsize =(10, 10))
  
# creating multiple plots in a 
# single plot
sub1 = plt.subplot(2, 2, 1)
sub2 = plt.subplot(2, 2, 2)
sub3 = plt.subplot(2, 2, 3)
sub4 = plt.subplot(2, 2, 4)
  
sub1.plot(a, 'sb')
  
# sets how the display subplot 
# x axis values advances by 1
# within the specified range
sub1.set_xticks(list(range(0, 10, 1)))
sub1.set_title('1st Rep')
  
sub2.plot(b, 'or')
  
# sets how the display subplot x axis
# values advances by 2 within the
# specified range
sub2.set_xticks(list(range(0, 10, 2)))
sub2.set_title('2nd Rep')
  
# can directly pass a list in the plot
# function instead adding the reference
sub3.plot(list(range(0, 22, 3)), 'vg')
sub3.set_xticks(list(range(0, 10, 1)))
sub3.set_title('3rd Rep')
  
sub4.plot(c, 'Dm')
  
# similarly we can set the ticks for 
# the y-axis range(start(inclusive),
# end(exclusive), step)
sub4.set_yticks(list(range(0, 24, 2)))
sub4.set_title('4th Rep')
  
# without writing plt.show() no plot
# will be visible
plt.show()

%matplotlib inline

import matplotlib.pyplot as plt

plt.style.use('seaborn-whitegrid')

import numpy as np

fig = plt.figure()
ax = plt.axes()

x = np.linspace(0, 10, 1000)

ax.plot(x, np.sin(x));

%matplotlib inline

import matplotlib.pyplot as plt

plt.style.use('seaborn-whitegrid')

import numpy as np

fig = plt.figure()

ax = plt.axes()

x = np.linspace(0, 10, 1000)

ax.plot(x, np.sin(x));

plt.plot(x, np.sin(x))

plt.plot(x, np.cos(x));
%matplotlib inline

import matplotlib.pyplot as plt

plt.style.use('seaborn-whitegrid')

import numpy as np

fig = plt.figure()

ax = plt.axes()

x = np.linspace(0, 10, 1000)

plt.plot(x, np.sin(x - 0), color='blue') # specify color by name

plt.plot(x, np.sin(x - 1), color='g') # short color code (rgbcmyk)

plt.plot(x, np.sin(x - 2), color='0.75') # Grayscale between 0 and 1

plt.plot(x, np.sin(x - 3), color='#FFDD44') # Hex code (RRGGBB from 00 to FF)

plt.plot(x, np.sin(x - 4), color=(1.0,0.2,0.3)) # RGB tuple, values 0 and 1

plt.plot(x, np.sin(x - 5), color='chartreuse'); # all HTML color names supported


%matplotlib inline

import matplotlib.pyplot as plt

plt.style.use('seaborn-whitegrid')

import numpy as np

fig = plt.figure()

ax = plt.axes()

x = np.linspace(0, 10, 1000)

ax.plot(x, np.sin(x));

plt.plot(x, np.sin(x))

plt.plot(x, np.cos(x));

plt.plot(x, x + 0, linestyle='solid')

plt.plot(x, x + 1, linestyle='dashed')

plt.plot(x, x + 2, linestyle='dashdot')

plt.plot(x, x + 3, linestyle='dotted');
2. Write programs to understand the use of Matplotlib for Working with Multiple Figures and Axes,
Adding Text, Adding a Grid and Adding a Legend.
# importing libraries
import matplotlib.pyplot as plt
import numpy as np
import math
  
# Get the angles from 0 to 2 pie (360 degree) in narray object
X = np.arange(0, math.pi*2, 0.05)
  
# Using built-in trigonometric function we can directly plot
# the given cosine wave for the given angles
Y1 = np.sin(X)
Y2 = np.cos(X)
Y3 = np.tan(X)
Y4 = np.tanh(X)
  
# Initialise the subplot function using number of rows and columns
figure, axis = plt.subplots(2, 2)
  
# For Sine Function
axis[0, 0].plot(X, Y1)
axis[0, 0].set_title("Sine Function")
  
# For Cosine Function
axis[0, 1].plot(X, Y2)
axis[0, 1].set_title("Cosine Function")
  
# For Tangent Function
axis[1, 0].plot(X, Y3)
axis[1, 0].set_title("Tangent Function")
  
# For Tanh Function
axis[1, 1].plot(X, Y4)
axis[1, 1].set_title("Tanh Function")
  
# Combine all the operations and display
plt.show()

3. Write programs to understand the use of Matplotlib for Working with Line Chart, Histogram, Bar
Chart, Pie Charts.

You might also like