云计算、AI、云原生、大数据等一站式技术学习平台

网站首页 > 教程文章 正文

matplotlib 笔记2:调整边界、多个子图、inset子图

jxf315 2025-04-05 19:35:37 教程文章 33 ℃

调整边界 plt.tight_layout()

遇到上面这种显示不全的问题,可以使用 plt.tight_layout() 方法, 这一行命令

plt.tight_layout() 

直接在绘图命令后面就可以,使用后效果如下

  • plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)

这个函数可以调节pad,w_pad,h_pad三个参数调整axes与figure的位置以及大小关系

多子图subplot

对于多个子图的绘制,可以使用 pyplot 中的 subplot() 和 subplots() 方法。

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rc
rc('text', usetex=True)
plt.rc('font',family='Times New Roman',size=15)

x=[1,2,3,4,5]
y1=[2,3,5,6,8]
y2=[3,4,6,7,9]

fig =plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax2 = fig.add_subplot(2,1,2)

ax1.plot(x,y1,'^-',c='red')
ax1.set_xlabel('xxx')
ax1.set_ylabel('yyy')

ax2.plot(x,y2,'v-',c='blue')
ax2.set_xlabel('xxx')
ax2.set_ylabel('yyy')
plt.show()
  • ax1 = fig.add_subplot(2,1,1) 义为 两行,一列,第一列图
  • ax2 = fig.add_subplot(2,1,2) 义为 两行,一列,第二列图
  • 效果

xxx被挡住了,可以用前面提到的tight_layout()

  • 加入一行命令 :plt.tight_layout()

正常显示

  • 横排:一行两列

大小不同的图形

fig =plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,3)
ax3 = fig.add_subplot(1,2,2)
ax1.plot(x,y1,'^-',c='red')
ax1.set_xlabel('x1')
ax1.set_ylabel('y1')

ax2.plot(x,y2,'v-',c='blue')
ax2.set_xlabel('x2')
ax2.set_ylabel('y2')

ax3.plot(x,y3,'o-',c='cyan')
ax3.set_xlabel('x3')
ax3.set_ylabel('y3')
plt.tight_layout()
plt.show()
  • 效果
  • 注释

红色图形占1/4,可以分布在一个两行两列的布局中的第1个:

ax1 = fig.add_subplot(2,2,1)

蓝色图形占1/4,可以分布在一个两行两列的布局中的第3个:

ax3 = fig.add_subplot(1,2,2)

青绿色图形占1/2,可以分布在一个一行两列的布局中的第2个:

ax2 = fig.add_subplot(2,2,3)

inset 子图

  • 需要导入库
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
  • inset子图绑定一个主图
ax2 = inset_axes(ax1,width=1.3, height=0.9)

这里ax2时inset,ax1是主图

  • 代码实例
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rc
rc('text', usetex=True)
plt.rc('font',family='Times New Roman',size=15)
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
x=[1,2,3,4,5]
y1=[2,3,5,6,8]
y2=[3,4,6,7,9]
fig =plt.figure()
ax1 = fig.add_axes([0.1,0.1,0.8,0.8])
ax1.plot(x,y1,'^-',c='red')
ax1.set_xlabel('x1')
ax1.set_ylabel('y1')

ax2 = inset_axes(ax1,width=1.3, height=0.9)
ax2.plot(x,y2,'v-',c='blue')
ax2.set_xlabel('x2')
ax2.set_ylabel('y2')

ax3 = inset_axes(ax1, width="30%", height="40%", loc=4)
ax3.plot(x,y3,'v-',c='orange')
ax3.set_xlabel('x3')
ax3.set_ylabel('y3')
plt.show()
  • 效果
最近发表
标签列表