You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Matplotlib子图设置独立坐标轴范围失效或子图消失问题

问题根因

  • 你在创建子图前调用的plt.axes(xlim=(-5,5), ylim=(-1,1))会先生成一个独立的全局坐标轴,后续生成3个垂直排列的子图时,第一个子图会覆盖该全局坐标轴的显示区域,因此会出现坐标轴限制不生效、子图消失的异常。
  • matplotlib的pyplot接口参数默认仅作用于当前激活的坐标轴,子图未创建时设置的坐标轴参数不会自动继承给后续生成的子图,要单独调整每个子图的范围,需要在对应子图的激活状态下设置参数。

修正代码

写法1:保持原pyplot调用风格

和你原有写法逻辑一致,仅调整坐标轴参数的设置位置:

# 导入依赖
import numpy as np
import matplotlib.pyplot as plt

# 计算绘图数据
x = np.linspace(-10,10,1000)
b = [2,3,4]
f = 3 # 单位:Hz

def y(z):
    return np.sin(2*np.pi*f*x) * np.sin(2*np.pi*b[z]*x)

# 绘图部分
plt.close("all")
%matplotlib inline
plt.figure(figsize = (12,10))

plt.subplot(3,1,1)
plt.plot(x,y(0))
plt.xlim(-5,5) # 为当前激活的第一个子图设置x轴范围
plt.ylim(-1,1) # 为当前激活的第一个子图设置y轴范围
plt.grid()
    
plt.subplot(3,1,2)
plt.plot(x,y(1))
plt.xlim(-5,5) # 可自定义不同的范围值
plt.ylim(-1,1)
plt.grid()

plt.subplot(3,1,3)
plt.plot(x,y(2))
plt.xlim(-5,5)
plt.ylim(-1,1)
plt.grid()

plt.show()

写法2:面向对象写法(更易维护)

直接获取每个子图的Axes对象单独操作,逻辑更清晰:

# 导入依赖、数据计算部分同上
plt.close("all")
%matplotlib inline
# 一次性生成画布和所有子图的Axes对象数组
fig, axs = plt.subplots(nrows=3, ncols=1, figsize=(12,10))

axs[0].plot(x, y(0))
axs[0].set_xlim(-5,5)
axs[0].set_ylim(-1,1)
axs[0].grid()

axs[1].plot(x, y(1))
axs[1].set_xlim(-5,5)
axs[1].set_ylim(-1,1)
axs[1].grid()

axs[2].plot(x, y(2))
axs[2].set_xlim(-5,5)
axs[2].set_ylim(-1,1)
axs[2].grid()

plt.show()

两种写法都支持你为每个子图设置完全独立的坐标轴范围,不会再出现参数不生效或者子图消失的问题。


内容的提问来源于stack exchange,提问作者lmixa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 07:36:01