Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Composition of multiple subgraphs

Sometimes we want to examine more than one aspect of the data. For example, to check the weather conditions of a region, we not only hope to obtain the relationship between time and temperature, but also need to pay attention to the relationship between time and wind power, PM2.5 and other aspects. At this time, we hope to display three different graphs of time-temperature, time-wind power and time-PM2.5 at the same time. Matplotlib provides a way to group multiple figures together.

import numpy as np
from matplotlib import pyplot as plt
t = np.linspace(-np.pi, np.pi, 1024)
grid_size = (4.2)
plt.subplot2grid(grid_size, (0.0), rowspan = 3, colspan = 1)
plt.plot(np.sin(2 * t), np.cos(0.5 * t), c = 'm')
plt.subplot2grid(grid_size, (0.1), rowspan = 3, colspan = 1)
plt.plot(np.cos(3 * t), np.sin(t), c = 'c')
plt.subplot2grid(grid_size, (3.0), rowspan=1, colspan=3)
plt.plot(np.cos(5 * t), np.sin(7 * t), c= 'y')
plt.tight_layout()
plt.show()
Copy the code

Tips: Use plt.subplot2Grid () to define a grid with R rows and C columns. We can then render a graph into the defined grid. The plt.subplot2grid() function takes four common arguments:

  1. The first argument is the number of rows and columns of the grid, which is passed as a tuple. For example, if we want a grid with R rows and C columns, we need to pass (R, C).
  2. The second parameter determines the coordinates of the graph in the grid and is also passed as a tuple.
  3. Optional parametersrowspanDefines how many rows the graph will occupy.
  4. Optional parameterscolspanDefines how many columns the graph will occupy.

After calling plt.subplot2Grid (), the next call to the PLT drawing will draw a graph in the specified rectangular region, and similarly, to draw the next graph in another region of the grid, plt.subplot2Grid () will be called again. In the example, a 2×4 grid is defined. The first two figures occupy one column and three rows, and the third one two columns and one row. Once you have drawn all the graphs, you need to call Pyplot.tight_layout () to automatically arrange all the graphs by definition to make sure they don’t overlap each other.

Add a title for each subgraph

We can already combine multiple subgraphs into one graph, but each subgraph may also need its own title. We can use plt.title() to add a title to each subgraph:

import numpy as np
from matplotlib import pyplot as plt
def get_radius(t, params) :
    m, n_1, n_2, n_3 = params
    u = (m * t) / 4
    return (np.fabs(np.cos(u)) ** n_2 + np.fabs(np.sin(u)) ** n_3) ** (-1. / n_1)
grid_size = (3.4)
t = np.linspace(0.2 * np.pi, 1024)
for i in range(grid_size[0) :for j in range(grid_size[1]):
        params = np.random.randint(1.20+1, size = 4)
        r = get_radius(t, params)
        plt.subplot2grid(grid_size, (i, j), rowspan=1, colspan=1)
        plt.plot(r * np.cos(t), r * np.sin(t), c = 'c')
        plt.title('%d, %d, %d, %d' % tuple(params), fontsize = 'small')
plt.suptitle("Example of plt.suptitle")
plt.tight_layout()
plt.show()
Copy the code

Tips: The plt.title() function can provide a title for each graph, but at this point, if we need a title for the entire graph, we should use the plt.suptitle() function.

Another method of subgraph synthesis

The subgraph composition method above is generic and can be used to create complex layouts, but if we only need to draw multiple subgraphs in the same row or column, we can use more concise code:

import numpy as np
from matplotlib import pyplot as plt
t = np.linspace(-np.pi, np.pi, 1024)
fig, (ax0, ax1, ax2) = plt.subplots(ncols =3)
ax0.plot(np.sin(2 * t), np.cos(0.5 * t), c = 'c')
ax1.plot(np.cos(3 * t), np.sin(t), c = 'c')
ax2.plot(np.cos(3 * t), np.sin(2 * t), c = 'c')
plt.tight_layout()
plt.show()
Copy the code

The plt.subplots() function accepts two optional arguments, nCOLs and nrows, and returns a Figure object with an instance of the NCOLs * nROWS axis. Axis instances are arranged in a grid by NROWS, NCOLs columns.

A cleaner way to do it

Although both of the above methods can fulfill the application requirements of synthesizing subplots, we need more than that. We may want a more concise approach, and the plt.subplot() function is what we need.

import numpy as np
from matplotlib import pyplot as plt
def get_radius(t, params) :
    m, n_1, n_2, n_3 = params
    u = (m * t) / 4
    return (np.fabs(np.cos(u)) ** n_2 + np.fabs(np.sin(u)) ** n_3) ** (-1. / n_1)
grid_size = (3.4)
t = np.linspace(0.2 * np.pi, 1024)
for i in range(grid_size[0] * grid_size[1]):
    params = np.random.random_integers(1.20, size = 4)
    r = get_radius(t, params)
    plt.subplot(grid_size[0], grid_size[1], i+1)
    plt.plot(r * np.cos(t), r * np.sin(t), c = 'c')
    plt.title('%d, %d, %d, %d' % tuple(params), fontsize = 'small')
plt.suptitle("Example of plt.suptitle")
plt.tight_layout()
plt.show()
Copy the code

The plt.subplot() function takes three arguments, the number of rows, the number of columns, and the bit order of the subplot, which directly specifies how to divide the grid and the location index to plot.

Series of links

Matplotlib common statistical graph drawing

Matplotlib uses custom colors to draw statistics

Matplotlib controls line style and line width

Matplotlib custom style to draw beautiful statistics

Matplotlib adds text instructions to the graph

Matplotlib adds comments to the graph

Matplotlib adds auxiliary grids and auxiliary lines to the graph

Matplotlib adds custom shapes

Matplotlib controls the scale spacing and labeling of the coordinate axes

Matplotlib uses logarithmic scales and polar coordinates