Matplotlib - Introduction



Matplotlib is a powerful and widely-used plotting library in Python which enables us to create a variety of static, interactive and publication-quality plots and visualizations. It's extensively used for data visualization tasks and offers a wide range of functionalities to create plots like line plots, scatter plots, bar charts, histograms, 3D plots and much more. Matplotlib library provides flexibility and customization options to tailor our plots according to specific needs.

It is a cross-platform library for making 2D plots from data in arrays. Matplotlib is written in Python and makes use of NumPy, the numerical mathematics extension of Python. It provides an object-oriented API that helps in embedding plots in applications using Python GUI toolkits such as PyQt, WxPythonotTkinter. It can be used in Python and IPython shells. Jupyter notebook and web application servers also.

Matplotlib has a procedural interface named the Pylab which is designed to resemble MATLAB a proprietary programming language developed by MathWorks. Matplotlib along with NumPy can be considered as the open source equivalent of MATLAB.

Matplotlib was originally written by John D. Hunter in 2003. The current stable version is 2.2.0 released in January 2018.

The most common way to use Matplotlib is through its pyplot module.

The following are the in-depth overview of Matplotlib's key components and functionalities −

Components of Matplotlib

Plot Intro

Figure

A figure is the entire window or page that displays our plot or collection of plots. It acts as a container that holds all elements of a graphical representation which includes axes, labels, legends and other components.

Example

This is the basic plot which represents the figure.

import matplotlib.pyplot as plt
# Create a new figure
fig = plt.figure()

# Add a plot or subplot to the figure
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
Output
Figure

Axes/Subplot

A specific region of the figure in which the data is plotted. Figures can contain multiple axes or subplots. The following is the example of the axes/subplot.

Example

import matplotlib.pyplot as plt
# Creating a 2x2 grid of subplots
fig, axes = plt.subplots(nrows=2, ncols=2)

# Accessing individual axes (subplots)
axes[0, 0].plot([1, 2, 3], [4, 5, 6])  # Plot in the first subplot (top-left)
axes[0, 1].scatter([1, 2, 3], [4, 5, 6])  # Second subplot (top-right)
axes[1, 0].bar([1, 2, 3], [4, 5, 6])  # Third subplot (bottom-left)
axes[1, 1].hist([1, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5])  # Fourth subplot (bottom-right)
plt.show()

Output

Axes Subplot

Axis

An axis refers to the X-axis or Y-axis in a plot or it can also denote an individual axis within a set of subplots. Understanding axes is essential for controlling and customizing the appearance and behavior of plots in Matplotlib. The following is the plot which contains the axis.

Example

import matplotlib.pyplot as plt
# Creating a plot
plt.plot([1, 2, 3, 4], [10, 20, 25, 30])

# Customizing axis limits and labels
plt.xlim(0, 5)
plt.ylim(0, 35)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

Output

Axis

Artist

Artists refer to the various components or entities that make up a plot such as figures, axes, lines, text, patches, shapes (rectangles or circles) and more. They are the building blocks used to create visualizations and are organized in a hierarchy.

The below is the plot which resembles all the components of an artist.

Example

import matplotlib.pyplot as plt
# Create a figure and an axis (subplot)
fig, ax = plt.subplots()

# Plot a line (artist)
line = ax.plot([1, 2, 3], [4, 5, 6], label='Line')[0]

# Modify line properties
line.set_color('red')
line.set_linewidth(2.5)

# Add labels and title (text artists)
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_title('Artist Plot')
plt.legend()
plt.show()

Output

Artist

Key Features

  • Simple Plotting − Matplotlib allows us to create basic plots easily with just a few lines of code.

  • Customization − We can extensively customize plots by adjusting colors, line styles, markers, labels, titles and more.

  • Multiple Plot Types − It supports a wide variety of plot types such as line plots, scatter plots, bar charts, histograms, pie charts, 3D plots, etc.

  • Publication Quality − Matplotlib produces high-quality plots suitable for publications and presentations with customizable DPI settings.

  • Support for LaTeX Typesetting − We can use LaTeX for formatting text and mathematical expressions in plots.

Types of Plots

Matplotlib supports various types of plots which are as mentioned below. Each plot type has its own function in the library.

Name of the plot Definition Image
Line plot

A line plot is a type of graph that displays data points connected by straight line segments.

The plt.plot() function of the matplotlib library is used to create the line plot.

simple plot
Scatter plot

A scatter plot is a type of graph that represents individual data points by displaying them as markers on a two-dimensional plane.

The plt.scatter() function is used to plot the scatter plot.

simple plot
Line plot

A line plot is a type of graph that displays data points connected by straight line segments.

The plt.plot() function of the matplotlib library is used to create the line plot.

simple scatter
Bar plot

A bar plot or bar chart is a visual representation of categorical data using rectangular bars.

The plt.bar() function is used to plot the bar plot.

Bar Plot
Pie plot

A pie plot is also known as a pie chart. It is a circular statistical graphic used to illustrate numerical proportions. It divides a circle into sectors or slices to represent the relative sizes or percentages of categories within a dataset.

The plt.pie() function is used to plot the pie chart.

Pie Plot

The above mentioned are the basic plots of the matplotlib library. We can also visualize the 3-d plots with the help of Matplotlib.

Subplots

We can create multiple plots within a single figure using subplots. This is useful when we want to display multiple plots together.

Saving Plots

Matplotlib allows us to save our plots in various formats such as PNG, PDF, SVG etc.

Advertisements