How to draw multiple subplots with matplotlib:subplot function

created at 07-13-2021 views: 16

Problem description

matploglib can draw beautiful graphs. Sometimes, we want to compare a group of graphs together. Is there any good way?

The subplot provided in matplotlib can solve this problem well.

Introduction to subplot function

Under matplotlib, a Figure object can contain multiple subplots (Axes), which can be quickly drawn using subplot(). The calling form is as follows:

  • The entire drawing area of the chart is divided into numRows rows and numCols columns
  • Then number each subregion in the order from left to right and top to bottom, and the number of the upper left subregion is 1.
  • The plotNum parameter specifies the area where the created Axes object is located
subplot(numRows, numCols, plotNum)

If numRows = 2, numCols = 3, then the entire graph drawing style is a 2X3 picture area, expressed in coordinates as

(1, 1), (1, 2), (1, 3)
(2, 1), (2, 2), (2, 3)

At this time, when plotNum = 3, the indicated coordinates are (1, 3), which is the subgraph in the first row and third column

If numRows, numCols and plotNum are all less than 10, they can be abbreviated as an integer, for example, subplot(323) and subplot(3,2,3) are the same.

subplot creates an axis object in the area specified by plotNum. If the newly created axis overlaps the previously created axis, the previous axis will be deleted.

Sample program

regular division: 3*3

#!/usr/bin/env python
#!encoding=utf-8

import matplotlib
import matplotlib.pyplot as plt

if __name__ == '__main__':
    for i,color in enumerate("rgby"):
        plt.subplot(221+i, axisbg=color)

    plt.show()

Sample image

Irregular division

But sometimes our division is not regular, such as the following form

Irregular division

How should this be divided?

  • Divide the entire table into 2*2
    The first two are simple, they are (2, 2, 1) and (2, 2, 2)
  • But what about the third picture, it occupies (2, 2, 3) and (2, 2, 4)
  • The display needs to be re-divided, according to 2 * 1
  • The first two pictures occupy the position (2, 1, 1)
  • So the third picture occupies the position (2, 1, 2)

How irregular division implemented

code

#!/usr/bin/env python
#!encoding=utf-8

import matplotlib.pyplot as plt
import numpy as np



def f(t):
    return np.exp(-t) * np.cos(2 * np.pi * t)

if __name__ == '__main__' :
    t1 = np.arange(0, 5, 0.1)
    t2 = np.arange(0, 5, 0.02)

    plt.figure(12)
    plt.subplot(221)
    plt.plot(t1, f(t1), 'bo', t2, f(t2), 'r--')

    plt.subplot(222)
    plt.plot(t2, np.cos(2 * np.pi * t2), 'r--')

    plt.subplot(212)
    plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

    plt.show()
created at:07-13-2021
edited at: 07-13-2021: