ax:
#添加子画布
1、第一种写法–subplot,
(1)创建单个子图
a=np.linspace(-2,2,10)
b=np.linspace(-3,3,15)
y=a*a
#subplot
fig,ax=plt.subplots()
ax.plot(a,y)
plt.show()
结果:
(2)用subplot—创建多个子图
fig, axs = plt.subplots(2, 1)
axs[0].plot(a,y)
axs[1].scatter(a,y)
fig.tight_layout()
plt.show()
结果如下:
2、第二种方法,用add_subplot-----创建多个子图
fig = plt.figure()
fig.add_subplot(231)
ax1 = fig.add_subplot(2,3,1)
ax2 = fig.add_subplot(232)
ax1.plot(a,y)
ax2.scatter(a,y)
plt.show()
但是这样的画,中间 那两个子图太小了,原因是因为我是创建的23的矩阵,一共六张图,如果只想两张图的大小,只需要改成(211)变成21的矩阵,一共2张图,如下结果:
fig = plt.figure(figsize=(5,5))#这个只能改变外面的画布大小,不能改变子图
fig.add_subplot(211)
ax1 = fig.add_subplot(2,1,1)
ax2 = fig.add_subplot(2,1,2)
ax1.plot(a,y)
ax2.scatter(a,y)
plt.show()
结果如下:
二者区别:
区别在于:
(1)使用 .add_subplot()函数,首先要先创建一个figure对象,通过对象调用这个函数;.subplot()直接创建
(2).add_subplot()函数实际功能是:“添加Axes到图中作为子图布置的一部分”;而.subplot()则是“在当前图中添加子图
三、新增子区域
文章见这篇博主,讲得非常好,批注来源:
https://blog.csdn.net/weixin_42969619/article/details/99477275?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522162571180016780255218595%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=162571180016780255218595&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allfirst_rank_v2~rank_v29-1-99477275.first_rank_v2_pc_rank_v29_1&utm_term=%E6%80%8E%E4%B9%88%E5%88%9B%E5%BB%BA2%E4%B8%AA%E5%A4%A7%E5%B0%8F%E4%B8%80%E6%A0%B7%E7%9A%84%E5%AD%90%E5%9B%BE&spm=1018.2226.3001.4187
a=np.linspace(-2,2,10)
b=np.linspace(-3,3,15)
y=a*a
# 首先需要创建一个画布的对象
fig = plt.figure()
# 子区域从figure 10%的位置开始绘制, 宽高延伸figure的80%
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
ax11 = fig.add_axes([left, bottom, width, height]) # main axes
ax1=ax11.plot(a,y)
# 子区域从figure 20%+60% 的位置开始绘制, 宽高增长figure的25%
ax12= fig.add_axes([0.4, 0.6, 0.25, 0.25]) # inside axes
ax2=ax12.scatter(a,y)
plt.show()
结果如下: