All about MatPlotlib

aziafrin

Aziza Afrin

Posted on June 24, 2023

All about MatPlotlib

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

Installation

Install and import matplotlib with following code:

!pip install matplotlib
Enter fullscreen mode Exit fullscreen mode
import matplotlib.pyplot as plt
Enter fullscreen mode Exit fullscreen mode

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.

import numpy as np
x=np.linspace(0,5,11)
y=x**2
Enter fullscreen mode Exit fullscreen mode

And now plot x and y.

#functional method for plot
plt.plot(x,y,'r')   
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Title')
Enter fullscreen mode Exit fullscreen mode

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

Multiplot

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

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

plt.subplot(1,2,2)
plt.plot(y,x,'b')
Enter fullscreen mode Exit fullscreen mode

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.

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')
Enter fullscreen mode Exit fullscreen mode

We can also plot a figure on another plot like this:

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')
Enter fullscreen mode Exit fullscreen mode

Multiple plot in one frame

Sub Plots

We can also create sub plots like functional approach.

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")

Enter fullscreen mode Exit fullscreen mode

Sub plots

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).
fig = plt.figure(figsize=(8,4), dpi=100)
Enter fullscreen mode Exit fullscreen mode

Saving Figure

Simply save the produced figure with:

fig.savefig("filename.png", dpi=200)
Enter fullscreen mode Exit fullscreen mode

Legends, labels and titles

The legends, labels and titles of the figure can also be controlled.

#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)
Enter fullscreen mode Exit fullscreen mode
# 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
Enter fullscreen mode Exit fullscreen mode

Plot Appearance

The plot appearance can also be controlled by matplotlib.

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

Enter fullscreen mode Exit fullscreen mode

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

#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)

Enter fullscreen mode Exit fullscreen mode

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

#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="-.")

Enter fullscreen mode Exit fullscreen mode

Marker

Different markers can also be added to the plotted line.

#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="-.")

Enter fullscreen mode Exit fullscreen mode

An example of different makers:

Marker in plot
Code of this plot is available in the linked Kaggle notebook.

Axis Range Customization

We can customize the axis range for our convenience

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");
Enter fullscreen mode Exit fullscreen mode

Different Plots

Plots like histogram, boxplot, scatter plot can also be produced with matplotlib.

data = [np.random.normal(0, std, 100) for std in range(1, 4)]

# rectangular box plot
plt.boxplot(data,vert=True,patch_artist=True);   
Enter fullscreen mode Exit fullscreen mode

The box plot

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

Happy Learning!❤️

Aziza Afrin

💖 💪 🙅 🚩
aziafrin
Aziza Afrin

Posted on June 24, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related