bing
Flat 10% & upto 50% off + 10% Cashback + Free additional Courses. Hurry up
×
UPTO
50%
OFF!
Intellipaat
Intellipaat
  • Live Instructor-led Classes
  • Expert Education
  • 24*7 Support
  • Flexible Schedule

Learn how to plot with Matplotlib

Handling of data is a skillful art. In the trending technological world there is massive amount of data that is being consumed as well as wasted. But, handling these data in a rather effective manner, becomes the main goal of data science. We can make use of various programming languages to deal with the datasets that require operations to be done on them, like- calculating the statistics, sales, marketing, plotting on graphical platforms, etc.

The following content will enable you to get a detailed view on how data can be plotted using matplotlib.

Description on matplotlib

Plotting of data can be extensively made possible in an interactive way by matplotlib, which is a plotting library that can be demonstrated in python scripts. Plotting of graphs is a part of data virtualization hence, this property can be achieved by making use of matplotlib.

Matplotlib makes use of many general purpose GUI toolkits such as wxPython, Tkinter, Qt, etc. in order to provides an object oriented API for embedding plots into applications. John D. Hunter was the person who originally wrote matplotlib. And its lead developer is Michael Droettboom. One of the free and open source python library which is basically used for technical and scientific computing is SciPy. Matplotlib is used in SciPy as most scientific calculations may require plotting of graphs and diagrams.

Python(matplotlib) vs. MATLAB

Python Programming MATLAB
It is an open source programming language, free to use MATLAB is a commercial based platform. Hence, it is not free.
Matplotlib is more flexible and capable for plotting Plotting is comparatively not as flexible and capable as python plotting.
Python provides a large number of libraries to work with. It is tricky to add libraries and then work with in MATLAB
Python is an easy to read and powerful programming language MATLAB is not as powerful as python
Matplotlib plotting is faster in python Plotting of data requires time and effort.
Integrated development environment(IDE) need to be added additionally IDE shall be provided within the MATLAB environment
Code can be used in multiple systems. It is portable Code portability is restricted
Namespace is supported in python Core of MATLAB does not support namespace

Syntax and basic example of matplotlib

 

import matplotlib.pyplot as pltPyplot is basically used for plot or figure manipulation.
Matplotlib.pyplot enables matplotlib to operate just like MATLAB.

Example:

import matplotlib.pyplot as plt
plt.plot([1,1])
plt.plot([2,2])
plt.plot([3,3])

Syntax and basic eample of matplotlib

The graph can be used to plot three straight lines. Hence, we make this possible by using the plotting library matplotlib.

 

1.  Plot: Illustration that can be represented using a graph

Import matplotlib.pyplot as plt
Import numpy as np
plt.plot([1,1])

plot illustration
When we take the plot parameters as [1,1] we get the above represented plot as the output.
2. Figure: A diagram or a shape that can be formed by a collection of plots in different dimensions
Example for figure():

import matplotlib.pyplot as plt
import numpy as np
plt.figure(1)
plt.plot([1,1])
plt.figure(2)
plt.plot([1,2])

Figure()
Figure(1) helps to print the first graph with the plot([1,1])
Figure(2) helps to print the second graph with plot([1,2])

3. Label: It is used to add labels or name to the respective x and y axis
4. Title: Used to display the title of the graph
Example for label() and title()

import numpy as np
import matplotlib.pyplot as plt
plt.plot([1,2,1,2])
plt.title(‘GRID REPRESENTATION’)
plt.xlabel(‘X-axis’)
plt.ylabel(‘Y-axis’)

Label and title example

In the above graph the horizontal axis is labelled as X-axis and the vertical axis is labelled as Y-axis and the title is displayed as GRID REPRESENTATION.

5. Grid: It is a collection of objects and functions which is concerned with 3 dimensional data.
Example for grid

import numpy as np
import matplotlib.pyplot as plt
plt.plot([1,2,1,2])
plt.xlabel(‘X-axis’)
plt.ylabel(‘Y-axis’)
plt.grid()

Grid example
A grid based representation is displayed in the above output and this helps to locate specific regions in the graph.
6. Subplot: A function subplot() can be called to plot multiple plots in the same figure.
Example for subplot

import matplotlib.pyplot as plt
import numpy as np
plt.subplot(2,1,1)
plt.plot([1,4])
plt.subplot(2,1,2)
plt.plot([2,2])

Subplot

The above representation is how subplots are obtained where, two subplots are plotted in the same figure.
Data science masters program

Plot manipulation description

 

  • Plot creation: This depends on the type of module that can be used in python. Creating a plot is the key aspect of plotting where we decide the plot upon which a figure is constructed. Figure and axes initialization is also carried out under plot creation.
  • Plot routines: Visualization techniques of viewing data from the simplest form to advanced form are a part of plot routines
  • Plot customization: This includes adding of plot titles, legends, axes labels, layouts, etc.
  • Also, the manipulation of plots includes Saving of plots, clearing the content, displaying the figures, clearing axes, etc.
  • Images, colors and text are some of the best features that can be included within the plot

 

Matplotlib Plotting ways (Types)

There are various plotting techniques or ways of plotting that can be carried out on the data provided and some of these plotting types are-

Line Plott

The plotting of a frequency of data along a line can be represented using line plot. It is one of the simplest and commonly used plotting methods. Line plotting is a primitive plotting technique that we have been using as it was the first plotting method that was introduced.

Let us now look at a real time scenario:

Consider a survey to be done on how much distance the following vehicles have covered in a span of 5 days. And the data collected can be plotted in different plotting methods.

I have made use of jupyter notebook to run the codes to represent the following data in plots.

BIKES

DAYS

DISTANCE COVERED IN KMS

ENFIELD

HONDA

YAHAMA

KTM

DAY 1 50 80 70 80
DAY 2 40 20 20 20
DAY 3 70 20 60 20
DAY 4 80 50 40 50
DAY 5 20 60 60 60

Example for line plot

import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [50,40,70,80,20]
y2 = [80,20,20,50,60]
y3 = [70,20,60,40,60]
y4 = [80,20,20,50,60]
plt.plot(x,y,’g’,label=’Enfield’, linewidth=5)
plt.plot(x,y2,’c’,label=’Honda’,linewidth=5)
plt.plot(x,y3,’k’,label=’Yahama’,linewidth=5)
plt.plot(x,y4,’y’,label=’KTM’,linewidth=5)
plt.title(‘bike details in line plot’)
plt.ylabel(‘ Distance in kms’)
plt.xlabel(‘Days’)
plt.legend()

line plot
Various lines are represented in the above graph and each line is denoted with a unique color. The line representing Honda has been overwritten upon by the line representing KTM since, both the vehicles have covered same distance in their respective days.

Bar Chart Plot

Categorical data can be represented in rectangular blocks with different height and length proportional to the values. Such a type of representation is called a bar chart. Bar charts can be used to plot data in both vertical and horizontal manner.
Example for Bar plot

import matplotlib.pyplot as plt
plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],
label=”Enfield”,width=.5)
plt.bar([0.26,1.25,2.25,3.25,4.25],[80,20,20,50,60],
label=”Honda”, color=’r’,width=.5)
plt.bar([0.31,1.5,2.5,3.5,4.5],[70,20,60,40,60],
label=”Yamaha”, color=’y’,width=.5)
plt.bar([.75,1.75,2.75,3.75,4.75],[80,20,20,50,60],
label=”KTM”, color=’g’,width=.5)
plt.legend()
plt.xlabel(‘Days’)
plt.ylabel(‘Distance (kms)’)
plt.title(‘Bikes details in BAR PLOTTING’)

Bar plot
The above plotting shows the bar representation of the given scenario where the mentioned bikes are symbolized using different colors and each colored block shows the distance covered by the respective bikes on every particular day for a period of 5 days.

Area Plot

This type of plotting is basically used for quantitative data. Line chart forms the basis of an area plot where, the region between the axis and the line is represented by colors.
Example of area plot

import matplotlib.pyplot as plt
days = [1,2,3,4,5]
Enfield =[50,40,70,80,20]
Honda = [80,20,20,50,60]
Yahama =[70,20,60,40,60]
KTM = [80,20,20,50,60]
plt.plot([],[],color=’k’, label=’Enfield’, linewidth=5)
plt.plot([],[],color=’c’, label=’Honda’, linewidth=5)
plt.plot([],[],color=’y’, label=’Yahama’, linewidth=5)
plt.plot([],[],color=’m’, label=’KTM’, linewidth=5)
plt.stackplot(days, Enfield, Honda, Yahama, KTM, colors=[‘k’,’c’,’y’,’m’])
plt.xlabel(‘Days’)
plt.ylabel(‘Distance in kms’)
plt.title(‘Bikes deatils in area plot’)
plt.legend()

Area plot

The above represented graph shows how an area plot can be plotted using the bike and its distance covered scenario. Each shaded area in the graph shows a particular bike with the frequency variations denoting the distance covered by the bike on different days.

Pie Plot

Statistical data can be represented in a circular graph where the circle is divided into portions that denote particular data, that is, each portion can be called a slice and these slices are proportional to the values in the data. This sort of plot can be mainly used in mass media and business.
Example for pie plot

import matplotlib.pyplot as plt
days = [1,2,3,4,5]
Enfield =[50,40,70,80,20]
Honda = [80,20,20,50,60]
Yahama =[70,20,60,40,60]
KTM = [80,20,20,50,60]
slices = [8,5,5,6]
activities = [‘Enfield’,’Honda’,’Yahama’,’KTM’]
cols = [‘c’,’g’,’y’,’b’]
plt.pie(slices,
labels=activities,
colors=cols,
startangle=90,
shadow= True,
explode=(0,0.1,0,0),
autopct=’%1.1f%%’)
plt.title(‘Bike details in Pie Plot’)

apie plot
In the above represented pie plot, the bikes scenario is illustrated and each slice represents the bike and the percentage of distance traveled by them.

Scatter Plot

Dot based plotting of multiple variables along x and y axis represent scatter plot. We can use different colors if necessary for better plotting and identification of dots.
Example for scatter plot

import matplotlib.pyplot as plt
days = [1, 2, 3, 4, 5]
Y1 = [50, 40, 70, 80, 20]
Y2=[80, 20, 20, 50, 60]
Y3=[70, 20, 60, 40, 60]
Y4=[80, 20, 20, 50, 60]
plt.scatter(days,Y1, label=’Enfield’,color=’r’)
plt.scatter(days,Y2,label=’Honda’,color=’b’)
plt.scatter(days,Y3,label=’Yahama’,color=’y’)
plt.scatter(days,Y4,label=’KTM’,color=’k’)
plt.xlabel(‘Days’)
plt.ylabel(‘Distance in kms’)
plt.title(‘ Bike details in Scatter Plot’)
plt.legend()

aScatter plot
In the above represented scatter plot, where various dots are scattered in the graph. Each colored dot represents the respective bike and the distance covered by the bikes.

3D Plot

Plotting of data along the X, Y and Z -axis to enhance the display of data and get a better view of plotted data, represents the three dimensional plotting. A three dimensional plotting is an advanced plotting technique that gives us a better view of the data representation along the three axis of the graph.

Example for 3d plot

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection=’3d’)
x = [1,2,3,4,5]
y = [50,40,70,80,20]
y2 = [80,20,20,50,60]
y3 = [70,20,60,40,60]
y4 = [80,20,20,50,60]
plt.plot(x,y,’g’,label=’Enfield’, linewidth=5)
plt.plot(x,y2,’c’,label=’Honda’,linewidth=5)
plt.plot(x,y3,’k’,label=’Yahama’,linewidth=5)
plt.plot(x,y4,’y’,label=’KTM’,linewidth=5)
plt.title(‘bike details in line plot’)
plt.ylabel(‘ Distance in kms’)
plt.xlabel(‘Days’)
plt.legend()

3D plot

In the above represented 3 dimensional graph. A line graph is illustrated in a three dimensional manner. We make use of a special library to plot 3D graphs which is given in the following syntax.
Syntax for plotting 3D graphs

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection=’3d’)

The import Axes3D is mainly used to create an axis by making use of the projection=3d keyword. This enables a three dimensional view of any data that can be written along with the above mentioned code.

Histogram plot

The plotting of numerical data in a precise manner by using rectangular blocks forms the basis of histogram plotting. A probability distribution can be estimated using histogram plot. The data is mostly represented in a continuous manner based on the dataset provided to plot the graph.
Example for histogram plot

import matplotlib.pyplot as plt
days = [50,80,70,80,40,20,20,20,70,20,60,20,80,50,40,50,20,60,60,60]
bins = [0,10,20,40,50,60,70,80,90,100]
plt.hist(days, bins, histtype=’stepfilled’, rwidth=0.88)
plt.xlabel(‘Distance in kms’)
plt.ylabel(‘kilometer count’)
plt.title(‘bike details Histogram’)

Histogram
The represented graph of a histogram shows the stepfill pattern. There are various histypes that can be used such as, bar, step, stepfill, etc. Histogram does not include spaces between the blocks. It is a continuous structure denoting the distance count that is the number of times the same distance is covered within a span of five days by the bikes along the Y-axis and the kilometer distance along X-axis.

Conclusion

This tutorial has shown you how to work with matplotlib and how to implement various types of plotting techniques. Hopefully, this tutorial served as a good demonstration about what is possible by using matplotlib. Dealing with multiple or huge amount of data and representing them in graphs for better understanding shows a beneficial use of matplotlib in python.
From code representation to output generation and explaining the graphs have been carried out in the tutorial. So, I would suggest you to go through the examples and practice them to get a better insight on how the code works.
Learning to work in python by using matplotlib shall enable you to improve in quality assessment of various data that can be put in front of you to deal with. This shall ensure you to become successful in the domain of plotting data.

Previous Next

Download Interview Questions asked by top MNCs in 2019?

"0 Responses on Python Matplotlib Tutorial"

Leave a Message

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.
top

Sales Offer

Sign Up or Login to view the Free Python Matplotlib Tutorial.