Post

# Python - Matplotlib

## Introduction

Matplotlib is a plotting library for 2D graphics. It is used for creating static, animated, and interactive visualizations in Python. This is a kind of replacement for MATLAB. But if someone wishes to use MATLAB, then there are certain functions which are used to call Python functions from MATLAB. One of the examples is matlab.engine.start_matlab (This would start the MATLAB engine for python.) Matplotlib is built on NumPy array (to understand NumPy you can refer to - https://www.c-sharpcorner.com/article/getting-started-with-numpy/ and https://www.c-sharpcorner.com/article/numpy-array/ ), which is a multidimensional data visualization for 2D plots of arrays.

To import the library we use:

import matplotlib.pyplot

Comparison between MATLAB and MATPLOTLIB

As we get started with Matplotlib, we already mentioned that it is kind of replacement of MATLAB, so we should be aware of the challenges.
• So, MATLAB in some or other way is a global style and it contains various functions that do not needs import and are readily available at the top level.
• Since, Matplotlib is built on top of NumPy array it needs to incorporate NumPy routine as well. This is also a challenge.
• In Matplotlib, we have a module named, PYLAB- This brings all the classes and functions of NumPy and Matplotlib.pyplot together into a common namespace. Also, it clones the global nature of MATLAB.
Types of plots
• Line Plot- plot ()
• Bar Graph- bar ()
• Histogram- hist ()
• Scatter Plot- scatter ()
• Area plot- stackplot ()
• Pie plot-pie ()
Now let us understand how we plot these.

## Line Plot/ Line Chart

This is a kind of Graph or Curve Chart which represents the information in the form of data points which are connected through straight lines.

We use function, plot()- to plot the line chart. It has 2 arguments in it, plot(x,y)- x coordinates to the x-axis, y is coordinates of the y-axis

EXAMPLE
1. from matplotlib import pyplot as plt
2.
3. plt.plot([1,2,5],[5,8,7])    # Function to plot
4. plt.show()    # function to show the plot

So according to the above function plot (): 1st coordinates are (1,5), 2nd are (2,8) and 3rd are (5,7).

We can add as many coordinates we want; we can add title to a particular chart, we can also add title to the axis. For example,
1. from matplotlib import pyplot as plt
2.
3. x = [5,2,7,5,9]
4. y = [10,5,9,3,2]
5.
6. plt.plot(x,y)
7. plt.title('Line Chart')    # Adding title to the Plot
8. plt.ylabel('Y axis')    # Adding title to Y-Axis
9. plt.xlabel('X axis')    # Adding title to X-Axis
10. plt.show()
We can also plot a simple plot of angle in as well.
1. from matplotlib import pyplot as plt
2. import numpy as np
3. import math
4.
5. x=np.arange(0, math.pi, 0.01)
6. y=np.cos(x)
7. plt.plot(x,y)
8. plt.show()
We can plot more than one line into line chart, we can also make it colourful

Markers

‘.’ – point marker, ‘o’- circle, ‘*’- star, ‘^’- triangle_up, ‘p’- pentagon, ‘s’- square, ‘+’-plus, ‘D’- Diamond, ‘|’- vline …. And many more.

Colors

‘b’ -blue , ‘g’- green , ‘r’-red , ‘y’- yellow , ‘k’- black , ‘m’- magenta, ‘w’- white, ‘c’- cyan

Line styles

‘-‘ (solid line), ‘- -‘ (Dashed line) , ‘-.’ (Dash dot line) , ‘:’ (Dotted line)

We should use it in format '[marker][line][colour]'
1. from matplotlib import pyplot as plt
2. import numpy as np
3. import math
4.
5. x1 = [1,17,27]
6. y1 = [6,18,2]
7.
8. x2 = [6,9,30]
9. y2 = [1,15,5]
10.
11. x3 = [52251430]
12. y3 = [1042083]
13.
14. x=np.arange(0, math.pi*100.10)
15. y=np.sin(x)
16.
17. plt.plot(x1,y1,'g',label='line one')
18. plt.plot(x2,y2,'c',label='line two',linewidth=5)
19. plt.plot(x,y,'g--',label='sine wave')
20. plt.plot(x3,y3,'m:',label='line three',linewidth=5)
21. plt.title('Multiple Data')
22. plt.ylabel('Price')
23. plt.xlabel('Growth')
24.
25. plt.legend()    #To show the upper top corner box (legend)
26. plt.grid(True,color='k')    # To print the plot in grid style in background
27.
28. plt.show()

## Bar Plot

This type of plot is also known as Bar Chart or Bar Graph which is a graphical display of data using rectangular bars of different heights.

We use function, bar()- to plot the bar chart.

EXAMPLE
1. from matplotlib import pyplot as plt
2.
3. x = [52947]
4. y = [105842]
5.
6. plt.bar(x,y)
7. plt.show()
You can change the color of the bars, change the width and height, can perform the comparison tasks, and all similar as above.
1. from matplotlib import pyplot as plt
2.
3. plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],
4. label="2019", color='k',width=.5)
5.
6. plt.bar([0.75,1.75,2.75,3.75,4.75],[80,20,20,50,60],
7. label="2020", color='m',width=.5)
8.
9. plt.legend()
10. plt.xlabel('Months')
11. plt.ylabel('Productivity (line of code)')
12. plt.title('Associate Data')
13.
14. plt.show()

## Histogram

This is a graphical display of data using bars of different heights. It is similar to a Bar Chart, but a histogram groups numbers into ranges.

We use function, hist()- to plot the Histogram

EXAMPLE
1. import matplotlib.pyplot as plt
2.
3. population_age = [22,55,62,45,21,22,34,42,42,4,2,102,95,85,55,110,120,70,65,55,111,115,80,75,65,54,44,43,42,48]
4. bins = [0,10,20,30,40,50,60,70,80,90,100]
5.
6. plt.hist(population_age, bins,color='c', rwidth=0.8)
7. plt.xlabel('Permanant Employees')
8. plt.ylabel('Training (yrs)')
9. plt.title('Histogram')
10.
11. plt.show()

## Scatter Plot

A scatter plot or scatter graph, scatter chart, scatter gram, or scatter diagram is a type of plot or mathematical diagram using Cartesian coordinates to display values for typically two variables for a set of data.

We use function, scatter()- to plot the scatter plot.

EXAMPLE
1. import matplotlib.pyplot as plt
2.
3. x = [1,2,3,4,5,6,7]
4. y = [3,4,5,6,6.5,7,8]
5.
6. x1=[8,8.5,9,9.5,10,10.5,11]
7. y1=[3,3.5,3.7,4,4.5,5,5.2]
8.
9. x2 = [4,3,6,7,7.5,8,6.5,8,7.5,5,5.5]
10. y2 = [4,4.5,5,6,5,4,4.5,4,6,5.5,4.5]
11.
12.
13. plt.scatter(x,y, label='high income low saving',color='r')
14. plt.scatter(x1,y1,label='low income high savings',color='b')
15. plt.scatter(x2,y2,label='lone',color='m')
16. plt.xlabel('saving*100')
17. plt.ylabel('income*1000')
18. plt.title('Scatter Plot')
19. plt.legend()
20.
21. plt.show()

## Area Plot

An Area plot/Chart is made by plotting a series of data points over time, connecting those data points with line segments, and then filling in the area between the line and the x-axis with color or shading.

We use function, stackplot()- to plot the area plot

EXAMPLE
1. import matplotlib.pyplot as plt
2.
3. days = [1,2,3,4,5]
4. sleeping =[7,8,6,11,7]
5. eating = [2,3,4,3,2]
6. working =[7,8,7,2,2]
7. playing = [8,5,7,8,13]
8.
9. plt.plot([],[],color='m', label='Sleeping', linewidth=5)
10. plt.plot([],[],color='c', label='Eating', linewidth=5)
11. plt.plot([],[],color='k', label='Working', linewidth=5)
12. plt.plot([],[],color='b', label='Playing', linewidth=5)
13.
14. plt.stackplot(days, sleeping,eating,working,playing, colors=['m','c','k','b'])
15. plt.xlabel('Hours')
16. plt.ylabel('Days')
17. plt.title('Stack Plot')
18. plt.legend()
19.
20. plt.show()

## Pie Plot

A Pie Chart is in the form of a pie which is a circular statistical graph divided into slices to illustrate numerical proportion

We use function, pie()- to plot the pie plot.

Pie() function includes various arguments,
• Sizes - Sizes is the area in which a particular label will cover within a whole pie.
• Labels - Labels are the categories in which you want the pie chart to be divided into.
• Colors - Colours are specified w.r.t every label
• Startangle -This makes the plotting right in the top middle of the pie chart. The elements are plotted sequentially in a clockwise manner if we use startangle=90, if we use startangle=180; it would populate the first element on the top with a 180-degree angle and then goes counterclockwise.
• Shadow - This will add a shadow type outline to the pie chart, if shadow= True, if shadow= False; Then there would be no outline or shadow we will just see white spaces between the labels.
• Explode - This will explode out the slice from the pie chart like- explode= (0,0,0.1,0), This we explode out only the 3rd slice.
• Autopct - This will add percentages to each of the constituents of the pie chart, like if we use autopct='%1.2f%%' the percentage is formatted to the hundredths place, if we use autopct='%1.3f%%' the percentage is formatted to the thousandths place
EXAMPLE
Before wrapping up Matplotlib, we should be aware that it is very difficult to use Matplotlib in other languages as it is restricted to Python only; one of the major reasons could be that it is heavily reliant on NumPy Library.

## SUMMARY

We learned about Matplotlib Library in Python which used to plot 2D graphics. Now practice plotting various graphs using the above information and apart from these plots, we can plot multiple plots. Do Practice!

I hope this article will help you further in Learning Python - Matplotlib.

Feedback or queries related to this article are most welcome.

Thanks for reading.

Recommended Free Ebook
Similar Articles