matplotlib学习笔记_subplot

subplot

  1. 基本用法
plt.subplot(nrows, ncols, index)
#nrows 与 ncols 表示要划分几行几列的子区域(nrows*nclos表示子图数量)
#index 的初始值为1,用来选定具体的某个子区域
#如果新建的子图与现有的子图重叠,那么重叠部分的子图将会被自动删除,
#因为它们不可以共享绘图区域。
plt.subplot(2,2,1)
x = np.arange(0,math.pi*2,0.05)
plt.plot(x,np.sin(x),'y-')
plt.subplot(2,2,4)
plt.plot(x,np.cos(x),'b.')
  1. add_subplot(nrows,ncols,index)
#fig.add_subplot()
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.plot(x,sin(x))
ax1.set_title('wave')
ax2 = fig.add_subplot(2,2,2)
ax2.plot(x,cos(x))
ax2.set_title('wave2')
  1. 使用add_axes也可以达到同一画布添加多个图形的效果
#使用add_axes()添加多幅图
import matplotlib.pyplot as plt
import math
import numpy as np
x = np.arange(0,math.pi*2,0.05)
fig = plt.figure()
ax1 = fig.add_axes([0,0,1,1])
ax1.plot(x,np.sin(x))
ax2 = fig.add_axes([.5,0.5,.5,.5])
ax2.plot(x,np.cos(x))
plt.show()

subplots()

它的使用方法和 subplot() 函数类似。其不同之处在于,subplots() 既创建了一个包含子图区域的画布,又创建了一个 figure 图形对象,而 subplot() 只是创建一个包含子图区域的画布。

fig , ax = plt.subplots(nrows, ncols)
#函数的返回值是一个元组,包括一个图形对象和所有的 axes 对象。
#其中 axes 对象的数量等于 nrows * ncols,且每个 axes 对象
#均可通过索引值访问(从1开始)。
import matplotlib.pyplot as plt
import numpy as np
import math
fig,ax = plt.subplots(2,2)
ax[0,1].plot(x,np.sin(x))
ax[1,0].plot(x,np.cos(x))

subplot2grid()

#plt.subplot2grid(shape, location, rowspan, colspan)
#shape:把该参数值规定的网格区域作为绘图区域;
#location:在给定的位置绘制图形,初始位置 (0,0) 表示第1行第1列;
#rowsapan/colspan:这两个参数用来设置让子区跨越几行几列。
import matplotlib.pyplot as plt
import numpy as np
import math
a1 = plt.subplot2grid((3,3),(0,0),colspan=2)
a2 = plt.subplot2grid((3,3),(0,2),rowspan=3)
a3 = plt.subplot2grid((3,3),(1,0),colspan=2,rowspan=2)
x = np.arange(0,math.pi*2,0.05)
a1.plot(x,sin(x))
a2.plot(x,cos(x))
a3.plot(x,tan(x))

posted on   朝朝暮Mu  阅读(78)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示