All about MatPlotlib
Aziza Afrin
Posted on June 24, 2023
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
import matplotlib.pyplot as plt
Intro
Let's start creating plot. We can go for two different approaches:
Functional Method
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
And now plot x and y.
#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.
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')
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')
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')
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")
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)
Saving Figure
Simply save the produced figure with:
fig.savefig("filename.png", dpi=200)
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)
# 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.
#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.
#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.
#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.
#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:
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");
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);
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
Posted on June 24, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.