SoFunction
Updated on 2025-03-06

Detailed tutorial on using Matplotlib for multi-graph drawing in Python

Preface

Matplotlib is a very powerful data visualization tool in Python, which can be used to generate various graphics from simple to complex. Whether it is processing single charts or multiple graphs, Matplotlib provides efficient support. In this article, we will explain how to use Matplotlib to draw multiple graphs to show multiple data analysis results on the same canvas.

1. Introduction to Matplotlib

Matplotlib is a data visualization library that can generate various types of charts such as bar charts, line charts, scatter charts, etc. In data analysis, we often encounter situations where we need to display data from multiple data sets or different dimensions in the same chart. Matplotlib's multi-graph drawing function is designed for this.

Install Matplotlib

If you have not installed Matplotlib, you can install it through the following command:

pip install matplotlib

2. Basic methods for multi-graph drawing using Matplotlib

Matplotlib provides two basic methods for multi-graph drawing:

  • subplot: Multiple small plots can be created in the same chart.
  • figureandaxes: This method is usedsubplots()The function generates a graph object and multiple axis objects, thereby drawing multiple graphics on the canvas.

Sample data

In the following examples, we will use some simple data to display it to facilitate understanding of the multi-graph drawing process.

import  as plt
import numpy as np

# Sample datax = (0, 10, 100)
y1 = (x)
y2 = (x)
y3 = (x)
y4 = (x + 1)

3. Create multi-graphs using subplot()

subplot()It is the most basic multi-graph drawing method in Matplotlib, and multiple sub-graphs can be arranged in the same window.subplot()The call method is as follows:

(n_rows, n_cols, index)
  • n_rows: Number of rows in the chart.
  • n_cols: Number of columns in the chart.
  • index: The position of the sub-picture, starting from 1.

Example 1: Create a 2x2 multi-graph layout

In the following example, we create a 2x2 layout with 4 plots, each showing a different function curve.

(figsize=(10, 8))

# First picture(2, 2, 1)
(x, y1, color='blue')
('Sine Function')

# The second picture(2, 2, 2)
(x, y2, color='green')
('Cosine Function')

# The third picture(2, 2, 3)
(x, y3, color='red')
('Tangent Function')

# The fourth picture(2, 2, 4)
(x, y4, color='purple')
('Logarithmic Function')

plt.tight_layout()  # Adjust the layout()

In this example,()Used to create a new graph,subplot()Functions draw each function curve at different positions in turn.tight_layout()The function is used to automatically adjust the spacing between subgraphs to ensure that the chart does not overlap.

Example 2: Subgraphs of asymmetric layout

If we don't want to layout in neat rows, we can use differentsubplotConfiguration implementation. For example, we can create a top part of the graph with 1 row and 2 columns, plus a graph that occupies the entire bottom.

(figsize=(10, 8))

# The left side of the upper part(2, 2, 1)
(x, y1, 'b-')
('Sine Function')

# The right sub-picture on the upper part(2, 2, 2)
(x, y2, 'g-')
('Cosine Function')

# The sub-picture that occupies the entire lower part(2, 1, 2)
(x, y3, 'r-')
('Tangent Function')

plt.tight_layout()
()

By adjustingsubplotWe can customize the layout of the chart for the number of rows, columns and index values.

4. Create multi-graphs using subplots()

subplots()Functions are a more flexible method. It can return a single subgraph containing all subgraphs at the same timefigureObject and oneaxesArrays to facilitate separate operation of each subgraph.

Example 3: Create a 2x2 multi-graph layout using subplots()

fig, axs = (2, 2, figsize=(10, 8))

# Draw Sine functionsaxs[0, 0].plot(x, y1, 'b')
axs[0, 0].set_title('Sine Function')

# Draw Cosine functionsaxs[0, 1].plot(x, y2, 'g')
axs[0, 1].set_title('Cosine Function')

# Draw Tangent functionsaxs[1, 0].plot(x, y3, 'r')
axs[1, 0].set_title('Tangent Function')

# Draw Logarithmic functionaxs[1, 1].plot(x, y4, 'purple')
axs[1, 1].set_title('Logarithmic Function')

plt.tight_layout()
()

Advantages

subplots()It allows us to control each subgraph more easily because the returnedaxesArrays allow us to manipulate specific subgraphs directly by index. This approach has more advantages for large projects, or when more control is required for each subgraph.

Example 4: Share the x-axis and y-axis

In multi-graph drawing, it is often desirable that multiple graphs share the x-axis or y-axis to make it clearer to compare different datasets. Can be insubplots()Used insharexandshareyStandards are implemented.

fig, axs = (2, 2, figsize=(10, 8), sharex=True, sharey=True)

# Draw different functionsaxs[0, 0].plot(x, y1, 'b')
axs[0, 0].set_title('Sine Function')

axs[0, 1].plot(x, y2, 'g')
axs[0, 1].set_title('Cosine Function')

axs[1, 0].plot(x, y3, 'r')
axs[1, 0].set_title('Tangent Function')

axs[1, 1].plot(x, y4, 'purple')
axs[1, 1].set_title('Logarithmic Function')

plt.tight_layout()
()

In this example, bysharex=Trueandsharey=True, we can share the x-axis and y-axis ranges of all subgraphs. For variables with similar ranges in multiple graphs, this setting simplifies the graph and makes it easier to interpret.

5. Use GridSpec for flexible layout

If you want to control the layout of subgraphs more flexibly, Matplotlib providesGridSpecModule, you can create subgraphs of different sizes and shapes in the same window.

Example 5: Create irregular layouts with GridSpec

import  as gridspec

(figsize=(10, 8))
gs = (3, 3)

# The upper left corner is occupies 2x2(gs[0:2, 0:2])
(x, y1, 'b-')
('Large Sine Plot')

# upper right corner(gs[0, 2])
(x, y2, 'g-')
('Small Cosine Plot')

#Center right image(gs[1, 2])
(x, y3, 'r-')
('Small Tangent Plot')

# The picture below occupies the entire bottom(gs[2, :])
(x, y4, 'purple')
('Logarithmic Plot')

plt.tight_layout()
()

existGridSpecIn  , we can define grids of 3 rows and 3 columns and place each subgraph into a different grid area to achieve a more complex layout.

6. Adjust the style and layout of multiple pictures

When drawing multiple pictures, you usually need to adjust the size of the chart, the spacing between sub-pictures, titles, etc. to optimize the display effect. Here are some commonly used adjustment methods:

  • Resize the canvas:usefigsize=(width, height)Controls the size of the canvas.
  • Automatically adjust layoutplt.tight_layout()The spacing between sub-pictures can be automatically adjusted to prevent titles or labels from overlapping.
  • Customize the spacing of sub-pictures:`plt.subplots_adjust(left, right, top

, bottom, wspace, hspace)` Manually adjust the spacing between sub-pictures.

Example 6: Adjust multi-picture spacing and overall layout

fig, axs = (2, 2, figsize=(10, 8))

# Add contents of each subpictureaxs[0, 0].plot(x, y1, 'b')
axs[0, 1].plot(x, y2, 'g')
axs[1, 0].plot(x, y3, 'r')
axs[1, 1].plot(x, y4, 'purple')

# Manually adjust the spacing between sub-picturesplt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1, wspace=0.3, hspace=0.4)
()

In multi-graph drawing, good layout and style adjustment can greatly improve the readability and aesthetics of the chart.

7. Summary

This article introduces the multi-graph drawing function of Matplotlib in Python. passsubplotandsubplotsMulti-graph layout can be easily realized and throughGridSpecFurther control the size and position of each subgraph. For multi-dimensional data presentation in data analysis, mastering these techniques can help us better understand data relationships and make the analysis results more intuitive.

This is the end of this article about using Matplotlib for multi-picture drawing in Python. For more related content on Python Matplotlib, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!