top of page

Matplotlib Example

Matplotlib is easy to use and an amazing visualizing library in Python. It is built on NumPy arrays and designed to work with the broader SciPy stack and consists of several plots like line, bar, scatter, histogram, etc.

In this article, we will learn about Python plotting with Matplotlib from basics to advance with the help of a huge dataset containing information about different types of plots and their customizations.

import matplotlib.pyplot as plt

# initializing the data
x = [10, 20, 30, 40]
y = [20, 30, 40, 50]

# plotting the data
plt.plot(x, y)

# Adding the title
plt.title("Simple Plot")

# Adding the labels
plt.ylabel("y-axis")
plt.xlabel("x-axis")
plt.show()

In the above example, the elements of X and Y provides the coordinates for the x axis and y axis and a straight line is plotted against those coordinates.

Figure class

Figure class is the top-level container that contains one or more axes. It is the overall window or page on which everything is drawn.

Syntax:

class matplotlib.figure.Figure(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None, constrained_layout=None)

Example 1:

# Python program to show pyplot module
import matplotlib.pyplot as plt
from matplotlib.figure import Figure

# Creating a new figure with width = 5 inches
# and height = 4 inches
fig = plt.figure(figsize =(5, 4))

# Creating a new axes for the figure
ax = fig.add_axes([1, 1, 1, 1])

# Adding the data to be plotted
ax.plot([2, 3, 4, 5, 5, 6, 6],
		[5, 7, 1, 3, 4, 6 ,8])
plt.show()


Example 2: Creating multiple plots


# Python program to show pyplot module
import matplotlib.pyplot as plt
from matplotlib.figure import Figure

# Creating a new figure with width = 5 inches
# and height = 4 inches
fig = plt.figure(figsize =(5, 4))

# Creating first axes for the figure
ax1 = fig.add_axes([1, 1, 1, 1])

# Creating second axes for the figure
ax2 = fig.add_axes([1, 0.5, 0.5, 0.5])

# Adding the data to be plotted
ax1.plot([2, 3, 4, 5, 5, 6, 6],
		[5, 7, 1, 3, 4, 6 ,8])
ax2.plot([1, 2, 3, 4, 5],
		[2, 3, 4, 5, 6])

plt.show()

Axes Class

Axes class is the most basic and flexible unit for creating sub-plots. A given figure may contain many axes, but a given axes can only be present in one figure. The axes() function creates the axes object. Let’s see the below example.

Syntax:


matplotlib.pyplot.axis(*args, emit=True, **kwargs)
# Python program to show pyplot module
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
# Creating the axes object with argument as
# [left, bottom, width, height]
ax = plt.axes([1, 1, 1, 1])

Example 2:

# Python program to show pyplot module
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
fig = plt.figure(figsize = (5, 4))

# Adding the axes to the figure
ax = fig.add_axes([1, 1, 1, 1])

# plotting 1st dataset to the figure
ax1 = ax.plot([1, 2, 3, 4], [1, 2, 3, 4])

# plotting 2nd dataset to the figure
ax2 = ax.plot([1, 2, 3, 4], [2, 3, 4, 5])
plt.show()



Setting Limits and Tick labels

You might have seen that Matplotlib automatically sets the values and the markers(points) of the x and y axis, however, it is possible to set the limit and markers manually. set_xlim() and set_ylim() functions are used to set the limits of the x-axis and y-axis respectively. Similarly, set_xticklabels() and set_yticklabels() functions are used to set tick labels


# Python program to show pyplot module
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
x = [3, 1, 3]
y = [3, 2, 1]

# Creating a new figure with width = 5 inches
# and height = 4 inches
fig = plt.figure(figsize =(5, 4))

# Creating first axes for the figure
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

# Adding the data to be plotted
ax.plot(x, y)
ax.set_xlim(1, 2)
ax.set_xticklabels((
"one", "two", "three", "four", "five", "six"))
plt.show()

Multiple Plots

Till now you must have got a basic idea about Matplotlib and plotting some simple plots, now what if you want to plot multiple plots in the same figure. This can be done using multiple ways. One way was discussed above using the add_axes() method of the figure class. Let’s see various ways multiple plots can be added with the help of examples.


Method 1: Using the add_axes() method

The add_axes() method figure module of matplotlib library is used to add an axes to the figure.

Syntax:

add_axes(self, *args, **kwargs)

Example:

# Python program to show pyplot module
import matplotlib.pyplot as plt
from matplotlib.figure import Figure

# Creating a new figure with width = 5 inches
# and height = 4 inches
fig = plt.figure(figsize =(5, 4))

# Creating first axes for the figure
ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])

# Creating second axes for the figure
ax2 = fig.add_axes([0.5, 0.5, 0.3, 0.3])

# Adding the data to be plotted
ax1.plot([5, 4, 3, 2, 1], [2, 3, 4, 5, 6])
ax2.plot([1, 2, 3, 4, 5], [2, 3, 4, 5, 6])
plt.show()

Method 2: Using subplot() method.

This method adds another plot to the current figure at the specified grid position.

Syntax:

subplot(nrows, ncols, index, **kwargs) subplot(pos, **kwargs) subplot(ax)

Example:

import matplotlib.pyplot as plt
# data to display on plots
x = [3, 1, 3]
y = [3, 2, 1]
z = [1, 3, 1]

# Creating figure object
plt.figure()

# adding first subplot
plt.subplot(121)
plt.plot(x, y)

# adding second subplot
plt.subplot(122)
plt.plot(z, y)


Note: Subplot() function have the following disadvantages –

  • It does not allow adding multiple subplots at the same time.

  • It deletes the preexisting plot of the figure.

Method 3: Using subplots() method

This function is used to create figure and multiple subplots at the same time.


Syntax:

matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)

Example:


import matplotlib.pyplot as plt

# Creating the figure and subplots
# according the argument passed
fig, axes = plt.subplots(1, 2)

# plotting the data in the 1st subplot
axes[0].plot([1, 2, 3, 4], [1, 2, 3, 4])

# plotting the data in the 1st subplot only
axes[0].plot([1, 2, 3, 4], [4, 3, 2, 1])

# plotting the data in the 2nd subplot only
axes[1].plot([1, 2, 3, 4], [1, 1, 1, 1])

Method 4: Using subplot2grid() method


This function give additional flexibility in creating axes object at a specified location inside a grid. It also helps in spanning the axes object across multiple rows or columns. In simpler words, this function is used to create multiple charts within the same figure.

Syntax:

Plt.subplot2grid(shape, location, rowspan, colspan)

Example:


import matplotlib.pyplot as plt
# data to display on plots
x = [3, 1, 3]
y = [3, 2, 1]
z = [1, 3, 1]

# adding the subplots
axes1 = plt.subplot2grid (
(7, 1), (0, 0), rowspan = 2, colspan = 1)
axes2 = plt.subplot2grid (
(7, 1), (2, 0), rowspan = 2, colspan = 1)
axes3 = plt.subplot2grid (
(7, 1), (4, 0), rowspan = 2, colspan = 1)

# plotting the data
axes1.plot(x, y)
axes2.plot(x, z)
axes3.plot(z, y)


Related Posts

See All

Mastering Lists in Python

Introduction Lists are one of the most fundamental and versatile data structures in Python. They allow you to store and manipulate collections of items, making them an essential tool for any Python pr

Python Anonymous Function

In Python, an anonymous function is a function that is defined without a name. It is also known as a lambda function because it is created using the `lambda` keyword. Anonymous functions are typically

Comments


bottom of page