matplotlib

建图(figure) → 画图(axes) → 保存/展示(fig.savefig(‘.png’)) → 关闭(plt.close(fig对象)) → 再建图

面向对象写法(推荐,最清晰)。先创建画布figure,再在figure上添加axes

  • 对象归属一目了然
  • 多图/多轴并行操作不串台
  • IDE 自动补全与类型提示
  • 代码可复用、可封装
import matplotlib.pyplot as plt

首先创建画布figure对象fig,然后通过四种方法添加axes

# 面向对象,使代码清晰
# 先创建figure,再在figure上创建axes

# 1) 创建 Figure,同时指定大小(英寸)
fig = plt.figure(figsize=(8, 10))
# 2) 设置内边距(左、下、右、上),值是 0–1 的百分比
fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95, wspace, hspace)
fig.suptitle('大标题', fontsize=14, fontweight='bold')

'''
方法一
ax1 = fig.add_subplot(2, 2, 1)  # 2×2 网格第 1 格
ax2 = fig.add_subplot(2, 2, (3, 4))  # 跨 3、4 两格

方法二
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])   # [left, bottom, width, height]

方法三
ax = fig.subplots(2, 3)

方法四
gs = fig.add_gridspec(2, 3, width_ratios=[2, 1, 1],height_ratios=[2, 1])
ax = fig.add_subplot(gs[0, :])    # 第 0 行跨 3 列
'''

再对axes设置详细的参数:标题,轴标题,x、y轴刻度标签,添加数据,图例,子图,网格,注释文字等

ax.set_title('子图标题', fontsize=14, pad=20)
ax.set_xlabel('X 轴标题', fontdict={'fontsize': 8, 'color': '#000000', 'fontweight': 600}, labelpad=10,loc='right')
ax.set_ylabel('Y 轴标题',fontdict={'fontsize': 8, 'color': '#000000', 'fontweight': 600}, labelpad=10,loc='top')

line1, = ax.plot(x, y1, lw=2, color='#1f77b4', label='sin(x)')
line2, = ax.plot(x, y2, lw=2, color='#ff7f0e', label='cos(x)')

ax.set_xlim([0, 10])    # 单侧限制 left=min  right=max
ax.set_ylim([-1.5, 1.5])    # 单侧限制 bottom=min top=max

ax.set_xticks([0, 1, 2, 3])
ax.set_xticklabels(['零', '壹', '贰', '叁'])   # 与 set_xticks 一一对应
ax.tick_params(axis='x',labelsize=12,labelcolor='red',rotation=45)
ax.set_yticks()
ax.set_yticklabels()
ax.tick_params(axis='y',
               labelsize=10,
               labelcolor='blue',
               right=True,        # 把刻度/标签画在右侧
               labelright=True,   # 右侧显示标签
               left=False,        # 左侧不画刻度
               labelleft=False)   # 左侧不画标签
ax.tick_params(axis='both', which='major', labelsize=6)  # 同时设置 x 和 y 轴主刻度标签字体大小

ax.legend(loc='upper right', frameon=True, shadow=True, fontsize=10,ncol=1, borderpad=0.5, labelspacing=0.5, title='图例')

# 添加文本
ax.text(0.5, 0.9, '局部最大值', transform=ax.transAxes,fontsize=11, color='red',bbox=dict(boxstyle="round,pad=0.3", facecolor='yellow', alpha=0.5))

局部放大图

# 主图
fig, ax = plt.subplots()
ax.plot(x, y)

# 定义要放大的区域
x1, x2 = 4.5, 5.5
y1, y2 = -1.2, 1.2

# 创建 inset axes:位置[left, bottom, width, height] 用 axes 比例
axins = ax.inset_axes([0.58, 0.6, 0.37, 0.37])   # 右上角小图
axins.plot(x, y)
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
axins.set_xticklabels([])   # 小图去掉刻度文字更清爽
axins.set_yticklabels([])

# 5) 画矩形框 + 连接线(一键完成)
ax.indicate_inset_zoom(axins, edgecolor="black")