个人网站不备案会怎么样,常州seo,哈尔滨建设工程信息网官方网站,太原网站建设方案优化Python中采用.add_subplot绘制子图的方法简要举例介绍 目录 Python中采用.add_subplot绘制子图的方法简要举例介绍一、Python中绘制子图的方法1.1 add_subplot函数1.2 基本语法#xff08;1#xff09;add_subplot的核心语法#xff08;2#xff09;add_subplot在中编程中的…Python中采用.add_subplot绘制子图的方法简要举例介绍 目录 Python中采用.add_subplot绘制子图的方法简要举例介绍一、Python中绘制子图的方法1.1 add_subplot函数1.2 基本语法1add_subplot的核心语法2add_subplot在中编程中的主要程序段 二、使用.add_subplot绘制子图举例2.1 问题描述2.2 程序代码2.3 运行结果 在Python中中绘图常会用到Matplotlib库本文讲简要举例说明利用Matplotlib 库中的函数add_subplot实现子图的绘制并说明其用法。
一、Python中绘制子图的方法
1.1 add_subplot函数
作为Matplotlib 库中的一个函数add_subplot用于在画布figure上添加子图subplot。这个方法比较有用可以帮助使用者在想要在一个图中创建多个子图。
1.2 基本语法
关于如何使用 add_subplot 本小节给出了使用主要方法
1add_subplot的核心语法
ax fig.add_subplot(nrows, ncols, plot_number)
其中: nrows: 表示网格中的行数。 ncols: 表示网格中的列数。 plot_number: 指定子图的位置。
例如fig.add_subplot(2, 3, 5)表示在2x3网格中的左下角放置一个子图则plot_number应为5。
2add_subplot在中编程中的主要程序段
import matplotlib.pyplot as plt
fig plt.figure()
ax_n fig.add_subplot(nrows, ncols, plot_number)
ax_n.plot(x_n, y_n)
plt.show()二、使用.add_subplot绘制子图举例
2.1 问题描述
为了 在2*2的图中绘制如下函数所表示的4个子图 { y 1 sin x x y 2 sin x 2 2 x y 3 sin x 3 3 x y 4 sin x 4 4 x \begin{cases} y_{1}\sin x x \\ y_{2}\sin x^2 2x \\ y_{3}\sin x^3 3x \\ y_{4}\sin x^4 4x\end{cases} ⎩ ⎨ ⎧y1sinxxy2sinx22xy3sinx33xy4sinx44x,其中 0 ≤ x 2 π 0\le x 2\pi 0≤x2π. 将使用Matplotlib工具库中add_subplot的进行绘图。
2.2 程序代码
示例代码 假设我们想在一个2x2的网格中绘制四个不同的图表
import matplotlib.pyplot as plt
import numpy as np# 1.数据准备x np.linspace(0, 2* np.pi, 400)
y1 np.sin(x )x
y2 np.sin(x ** 2)2*x
y3 np.sin(x ** 3)3*x
y4 np.sin(x ** 4)4*x# 2.创建一个新的图形对象
fig plt.figure()# 2.1 在2x2的网格中添加子图
ax1 fig.add_subplot(2, 2, 1) # 左上
ax2 fig.add_subplot(2, 2, 2) # 右上
ax3 fig.add_subplot(2, 2, 3) # 左下
ax4 fig.add_subplot(2, 2, 4) # 右下# 2.2.再各个子图中绘制数据ax1.plot(x, y1)
ax1.set_title(Subplot 1)ax2.plot(x, y2)
ax2.set_title(Subplot 2)ax3.plot(x, y3)
ax3.set_title(Subplot 3)ax4.plot(x, y4)
ax4.set_title(Subplot 4)plt.show()2.3 运行结果
比如将上述程序在PyCharm中运行结果如下 图1 采用.add_subplot绘制子图的运行结果