All about MatPlotlib
Tags: python, plot, programming
Published: 2023-06-24 16:57:31



## MatPlotlib
Today, we are gonna talk about a python library called **MatPlotlib**. It allows to create different types of visualizations. It also can produce animated and interactive plots with simple syntax. If you are interested to learn more about **MatPlotlib**, here is the link of the matplotlib official website: [matplotlib](http://https://matplotlib.org/)

## Installation
Install and import matplotlib with following code:
```py
!pip install matplotlib
```
```py
import matplotlib.pyplot as plt
```

## Intro
Let's start creating plot. We can go for two different approaches:

1. Functional Method 

2. Object Oriented Method


## 1. Functional Method 
Let's define two array **x** and **y**.
```py
import numpy as np
x=np.linspace(0,5,11)
y=x**2
```
And now plot x and y.
```py
#functional method for plot
plt.plot(x,y,'r')   
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Title')
```
Here,
**'r'** will gives a red coloured plotted line.
**plt.xlabel('X')** will label the x axis.
**plt.ylabel('Y')** will labl the y axis.
**plt.title('Title')** wiil gives a title for the plot.

![A basic matplotlib functional plot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sihf4xoi4thbx3aky43f.png)

### Multiplot
We can create several plot at a time using subplot. For example:

```py
plt.subplot(1,2,1)
plt.plot(x,y,'r')

plt.subplot(1,2,2)
plt.plot(y,x,'b')
```
Run this code on the linked kaggle notebook to see these subplot.


## 2. Object-Oriented Method
We have a lot more control on the figure comparing with functional approach. We start by creating an empty figure object and then adding feature simultaneously.

```py
fig=plt.figure()   #it will create an empty canvus figure

axes=fig.add_axes([0.1,0.1,0.8,0.8])

axes.plot(x,y)
axes.set_xlabel('X')
axes.set_ylabel('Y')
axes.set_title('Title of the plot')
```
We can also plot a figure on another plot like this:

```py
fig=plt.figure()    #it will create an empty canvus figure
axes1=fig.add_axes([0.1,0.1,0.8,0.8])
axes2=fig.add_axes([0.2,0.5,0.4,0.3])

axes1.plot(x,y)
axes1.set_title('Larger plot')

axes2.plot(y,x)
axes2.set_title('Smaller plot')
```

![Multiple plot in one frame](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3q66xcpedut3igqg4spw.png)

### Sub Plots
We can also create sub plots like functional approach.

```py
fig,axes=plt.subplots(nrows=1, ncols=2) #arranging plots in rows and column

axes[0].plot(y,x,'r')
axes[0].set_title("The red line")

axes[1].plot(x,y,'g')
axes[1].set_title("The green line")

```

![Sub plots](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wlyjwu0sp36kvno53i7e.png)

### Figure Size and DPI
We can also control the figure size and dpi of the plot.
* `figsize` is a tuple of the width and height of the figure in inches
* `dpi` is the dots-per-inch (pixel per inch). 

```py
fig = plt.figure(figsize=(8,4), dpi=100)
```
### Saving Figure
Simply save the produced figure with:

```py
fig.savefig("filename.png", dpi=200)
```
### Legends, labels and titles
The legends, labels and titles of the figure can also be controlled.

```py
#Legend

fig = plt.figure()

ax = fig.add_axes([0,0,1,1])

ax.plot(x, x**2, label="x**2")
ax.plot(x, x**3, label="x**3")
ax.legend(loc=3)
```

```py
# Lots of options for legend locations

ax.legend(loc=1) # upper right corner
ax.legend(loc=2) # upper left corner
ax.legend(loc=3) # lower left corner
ax.legend(loc=4) # lower right corner
ax.legend(loc=10) # center
ax.legend(loc=0) #let matplotlib to choose location

# Commonly used
ax.legend(loc=0) # let matplotlib decide the optimal location
fig
```
### Plot Appearance
The plot appearance can also be controlled by matplotlib.

```py
#using RGB hex code for diffrent colour
fig=plt.figure()
ax=fig.add_axes([0,0,1,1])
ax.plot(x,y,color='#FF8C10')

```

The line width and transparency of the plotted line can be controlled in matplotlib library.

```py
#setting alpha for transparency of the plotted line
fig=plt.figure()
ax=fig.add_axes([0,0,1,1])
ax.plot(x,y,color='#FF8C10',linewidth=8, alpha=0.6)

```

We can transform the plotted line from a simple line to a -. line or many more.

```py
#using ls or line style for different typs of plotted line
fig=plt.figure()
ax=fig.add_axes([0,0,1,1])
ax.plot(x,y,color='violet',lw=5,alpha=0.7,linestyle="-.")

```
### Marker
Different markers can also be added to the plotted line.

```py
#using ls or line style for different typs of plotted line
fig=plt.figure()
ax=fig.add_axes([0,0,1,1])
ax.plot(x,y,color='violet',lw=5,alpha=0.7,linestyle="-.")

```
An example of different makers:


![Marker in plot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/znw5g99cnqlv9atk3stp.png)
Code of this plot is available in the linked Kaggle notebook.

### Axis Range Customization
We can customize the axis range for our convenience 

```py
fig, axes = plt.subplots(1, 3, figsize=(12, 4))

axes[0].plot(x, x**2, x, x**3)
axes[0].set_title("default axes ranges")

axes[1].plot(x, x**2, x, x**3)
axes[1].axis('tight')
axes[1].set_title("tight axes")

axes[2].plot(x, x**2, x, x**3)
axes[2].set_ylim([0, 60])
axes[2].set_xlim([2, 5])
axes[2].set_title("custom axes range");
```

### Different Plots
Plots like histogram, boxplot, scatter plot can also be produced with matplotlib.
```py
data = [np.random.normal(0, std, 100) for std in range(1, 4)]

# rectangular box plot
plt.boxplot(data,vert=True,patch_artist=True);   
```

![The box plot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j51pmmtv8ih7uhg0em07.png)




You can practice more example at your own. The notebook link is given below. Follow this link to practice on your own.
Notebook Link: [https://www.kaggle.com/code/azizaafrin/matplotlib]
Github Link: [Github](https://github.com/aziafrin/python/blob/f259eb2f76808cb5d273f8974b16b2fdc497f170/matplotlib.ipynb)

Happy Learning!❤️

_Aziza Afrin_