Python中如何将多项式系数表达式加入图例并绘制计算点
解决方案
1. 多项式系数的格式转换
numpy的np.polyfit()返回的系数是从最高次项到常数项排列的(比如9阶拟合返回[c₉, c₈, ..., c₀]),要生成y = c₈x⁸ + c₇x⁷ + … + c₀格式的字符串,只需遍历系数并拼接对应项:
import numpy as np import matplotlib.pyplot as plt # 假设已有的测量数据 gain_meas = np.array([10, 12, 14, 16, 18, 20]) # 示例增益数据 pout_meas = np.array([30, 35, 42, 47, 51, 53]) # 示例输出功率数据 # 9阶多项式拟合 order = 9 coeffs = np.polyfit(gain_meas, pout_meas, order) # 生成多项式字符串 poly_str = "y = " for exp in range(order, -1, -1): coeff = coeffs[order - exp] # 处理符号与格式 if exp == order: poly_str += f"{coeff:.4f}x^{exp}" else: sign = "+" if coeff >= 0 else "-" term = f"x^{exp}" if exp != 0 else "" poly_str += f" {sign} {abs(coeff):.4f}{term}" # 替换为美观的Unicode上标(可选) superscripts = {"^9":"⁹", "^8":"⁸", "^7":"⁷", "^6":"⁶", "^5":"⁵", "^4":"⁴", "^3":"³", "^2":"²", "^1":"", "^0":""} for k, v in superscripts.items(): poly_str = poly_str.replace(k, v) # 处理x^1替换后的多余空格 poly_str = poly_str.replace("x ", "x")
2. 将多项式字符串加入图例
绘图时把生成的poly_str作为拟合曲线的图例标签即可:
# 绘制测量数据与拟合曲线 plt.scatter(gain_meas, pout_meas, label="测量数据") gain_fit = np.linspace(min(gain_meas), max(gain_meas), 100) pout_fit = np.polyval(coeffs, gain_fit) plt.plot(gain_fit, pout_fit, label=f"9阶拟合\n{poly_str}") # 绘制目标输出功率对应增益点(保留原有实现) target_pout = 52 # 构造多项式方程求解对应增益 eq_coeffs = np.append(coeffs, -target_pout) roots = np.roots(eq_coeffs) # 筛选有效实数解 valid_gain = [r.real for r in roots if np.isreal(r) and min(gain_meas) <= r.real <= max(gain_meas)] plt.scatter(valid_gain, [target_pout]*len(valid_gain), color="red", marker="*", label=f"52dBm对应增益") plt.xlabel("增益 (dB)") plt.ylabel("输出功率 (dBm)") plt.legend() plt.grid(True) plt.show()
注意事项
- 可调整
.4f的小数位数,匹配数据精度需求 - 若不需要Unicode上标,可跳过替换步骤,直接保留
x^n格式 - 求解目标增益时,务必筛选实数且在测量范围内的解,避免无效值
内容的提问来源于stack exchange,提问作者blast
相关产品推荐
相关产品推荐

