Python control库bode_plot如何调整画布尺寸并显示对数网格线
解决方案
你需要修改绘图相关的代码段,具体调整如下:
核心修改点
- 修正
plt.figure的调用方式,通过figsize参数指定画布尺寸,数值越大画布越大 - 绘制伯德图后获取子图对象,开启对数刻度网格,设置
which='both'同时显示主、次对数刻度的网格线
修改后完整可运行代码
import matplotlib.pyplot as plt import numpy as np import time plt.rcParams['font.size'] = 14 import os import control f = np.logspace(0,6,1000) w = 2*np.pi*f s = control.TransferFunction.s R1=31600 R2=5230 R3=4420 R4=5110 C1=10e-9 C2=1.8e-9 C3=150e-12 num = ((s*C2*(R1+R3)+1))*(s*C1*R2+1) den = (s*R1*C1)*(s*C2*R3+1)*(s*R2*C3+1) Hs = control.tf((num/den)) print(Hs) # 调整1:设置画布尺寸,可自定义(宽度, 高度)的数值,单位为英寸 plt.figure(figsize=(12, 9)) # 绘制伯德图,return_ax=True返回子图对象方便后续调整 out, mag_ax, phase_ax = control.bode_plot(Hs, w, dB=1, Hz=1, deg=1, plot=1, margins=1, return_ax=True) # 调整2:给幅值和相位子图都添加对数网格线 mag_ax.grid(which='both', axis='both', linestyle='--', alpha=0.7) phase_ax.grid(which='both', axis='both', linestyle='--', alpha=0.7) plt.show()
兼容调整说明
如果使用的control模块版本较低不支持return_ax参数,可以替换网格设置部分的代码为:
# 兼容旧版本control模块的网格设置 fig = plt.gcf() axes = fig.get_axes() axes[0].grid(which='both', axis='both', linestyle='--', alpha=0.7) axes[1].grid(which='both', axis='both', linestyle='--', alpha=0.7)
figsize=(12,9)的两个数值可自行调整,数值越大画布尺寸越大alpha参数控制网格线透明度,linestyle控制网格线样式,可按需修改
内容的提问来源于stack exchange,提问作者thaamike
相关产品推荐
相关产品推荐

