可视化基础,这个链接非常重要!!!


1.fig, ax = plt.subplots(figsize = (a, b))解析

在matplotlib一般使用plt.figure来设置窗口尺寸。

plt.figure(figsize=(a, b)) 

其中figsize用来设置图形的大小,a为图形的宽, b为图形的高,单位为英寸。、

但是如果使用plt.subplots,就不一样了。

fig, ax = plt.subplots(figsize = (a, b))

fig代表绘图窗口(Figure);ax代表这个绘图窗口上的坐标系(axis),一般会继续对ax进行操作。

fig, ax = plt.subplots()等价于:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

实例1

fig, ax = plt.subplots(1, 3, 1)

第一个1参数是子图的行数,第二个3参数是子图的列数
第三个1参数是代表第一个子图,如果想要设置子图的宽度和高度可以在函数内加入figsize值。

实例2

import numpy as np
import matplotlib.pyplot as plt

# 做1*1个子图,等价于"fig, ax = plt.subplot()",等价于"fig, ax = plt.subplots()"
fig, ax = plt.subplots(1, 1)
ax2 = ax.twinx()  # 让2个子图的x轴一样,同时创建副坐标轴。

# 作y=sin(x)函数
x1 = np.linspace(0, 2 * np.pi, 100)  # 表示在区间[0, 2π]之间取100个点作为横坐标
y1 = np.sin(x1)
ax.plot(x1, y1)

# 作y=cos(x)函数
x2 = np.linspace(0, 2 * np.pi, 100)
y2 = np.cos(x2)
ax2.plot(x2, y2)
plt.show()

在这里插入图片描述

2.plt.subplot()函数解析

plt.subplot()函数用于直接指定划分方式和位置进行绘图

pylab和pyplot有当前的图形(figure)和当前的轴(axes)的概念,所有的作图命令都是对当前的对象作用。可以通过gca()获得当前的轴(axes),通过gcf()获得当前的图形(figure)。

# 使用plt.subplot来创建小图. plt.subplot(221)表示将整个图像窗口分为2行2列, 当前位置为1.
plt.subplot(221)
# plt.subplot(222)表示将整个图像窗口分为2行2列, 当前位置为2.
plt.subplot(222) # 第一行的右图
# plt.subplot(223)表示将整个图像窗口分为2行2列, 当前位置为3.
plt.subplot(223)
# plt.subplot(224)表示将整个图像窗口分为2行2列, 当前位置为4.
plt.subplot(224)

注意:其中各个参数也可以用逗号,分隔开。第一个参数代表子图的行数;第二个参数代表该行图像的列数; 第三个参数代表每行的第几个图像。

import numpy as np
import matplotlib.pyplot as plt

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

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

在这里插入图片描述

'''如果不指定figure()的轴,figure(1)命令默认会被建立,
同样的如果你不指定subplot(numrows,numcols,fignum)的轴,subplot(111)也会自动建立。'''

import matplotlib.pyplot as plt
plt.figure(1) # 创建第一个画板(figure)
plt.subplot(211) # 第一个画板的第一个子图
plt.plot([1, 2, 3])
plt.subplot(212) # 第一个画板的第二个子图
plt.plot([4, 5, 6])
plt.figure(2) # 创建第二个画板
plt.plot([4, 5, 6]) # 默认子图命令是subplot(111)
plt.figure(1) # 调取画板1; subplot(212)仍然被调用中
plt.subplot(211) # 调用subplot(211)
plt.title('Easy as 1, 2, 3') # 做出211的标题

在这里插入图片描述
参考:


1.https://blog.csdn.net/TeFuirnever/article/details/93724227
2.https://blog.csdn.net/TeFuirnever/article/details/89842795



如果对您有帮助,麻烦点赞关注,这真的对我很重要!!!如果需要互关,请评论留言!
在这里插入图片描述


Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐