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

Matplotlib绘图报错:x与y维度不匹配,求切线绘图解决方案

问题:绘制曲线、切线及定点时出现维度不匹配错误

我正在进行中期项目,目标是求出并打印曲线f(x)=x²-26x-169过点A(0;-8788)的切线方程,随后在同一图中绘制f(x)、切线及点A。但绘图环节出现错误。

我的代码:

import sympy as sp
import numpy as np
from matplotlib import pyplot as plt

x,x0,y0,k= sp.symbols('x x0 y0 k')
fx = x ** 2 - 2 * 13 * x - 13 ** 2
df = sp.diff(fx, x)    
delta = df*(x-x0)+(y0)          
yy = delta.subs([(x0,0),(y0,-4*(13**3))])
y_tangentLine = delta.subs([(x0,0),(y0,-4*(13**3)),(df,k)])
y = yy - fx                  
sol = sp.solve( y, x)
for i in range(len(sol)):
    x1 = (sol[0])               
    x2 = (sol[1])
k1 = df.subs(x,x1)              
k2 = df.subs(x,x2)             
y1 = y_tangentLine.subs(k,k1)
y2 = y_tangentLine.subs(k,k2)
print("Equation of the tangent line 1 to the curve f(x) :", y1)
print("Equation of the tangent line 1 to the curve f(x) :", y2)
x = np.linspace(-500, 500,50)
fx = x ** 2 - 2 * 13 * x - 13 ** 2
y1 = x*(-26*math.sqrt(51) - 26) - 8788
plt.plot(x,fx)
plt.plot(0, -4*13**3,'rD')
plt.plot(x1,y1)
plt.title("Question 1c")
plt.show()

完整报错信息:

C:\Users\DELL\AppData\Local\Programs\Python\Python312\python.exe C:\Users\DELL\OneDrive\Desktop\python\demo.py 
Equation of the tangent line 1 to the curve f(x) : x*(-26*sqrt(51) - 26) - 8788
Equation of the tangent line 1 to the curve f(x) : x*(-26 + 26*sqrt(51)) - 8788
Traceback (most recent call last):
  File "C:\Users\DELL\OneDrive\Desktop\python\demo.py", line 92, in <module>
    c()
  File "C:\Users\DELL\OneDrive\Desktop\python\demo.py", line 87, in c
    plt.plot(x1,y1)
  File "C:\Users\DELL\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\pyplot.py", line 3575, in plot
    return gca().plot(
           ^^^^^^^^^^^
  File "C:\Users\DELL\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\axes\_axes.py", line 1721, in plot
    lines = [*self._get_lines(self, *args, data=data, **kwargs)]
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\DELL\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\axes\_base.py", line 303, in __call__
    yield from self._plot_args(
               ^^^^^^^^^^^^^^^^
  File "C:\Users\DELL\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\axes\_base.py", line 499, in _plot_args
    raise ValueError(f"x and y must have same first dimension, but "
ValueError: x and y must have same first dimension, but have shapes (1,) and (50,)

我是Python新手,已花费一周时间在该项目上,这是完成项目的最后一步,但我陷入了困境。查阅多篇帖子仍未解决,恳请提供解决思路!


解决思路与修正方案

错误原因

报错核心是绘图时x和y维度不匹配:x1是SymPy求解得到的单个标量值(形状(1,)),而y1是用长度为50的numpy数组x计算出来的数组(形状(50,)),matplotlib要求绘图的x、y序列长度必须一致。

另外代码还有几个小问题:

  • 变量名冲突:先把x定义为SymPy符号,后又赋值为numpy数组,容易混淆
  • 手动硬编码切线方程,容易出错且没必要
  • 缺少math模块导入,代码运行会报错

修正步骤

  1. 区分SymPy符号与numpy变量:把SymPy符号改为x_sym,避免和后续的numpy数组x冲突
  2. 用SymPy的lambdify工具将符号表达式转换为可处理numpy数组的函数,直接计算切线的y值,不用手动硬编码
  3. 绘图时,切线的x轴用我们生成的np.linspace数组,对应的y轴用转换后的函数计算,保证维度一致
  4. 补充导入math模块

修正后的完整代码

import sympy as sp
import numpy as np
import math
from matplotlib import pyplot as plt

# 用x_sym作为SymPy符号,避免和后续numpy数组x冲突
x_sym, x0, y0, k = sp.symbols('x x0 y0 k')
fx_sym = x_sym ** 2 - 2 * 13 * x_sym - 13 ** 2
df_sym = sp.diff(fx_sym, x_sym)    
delta = df_sym * (x_sym - x0) + y0          
# 代入点A(0, -8788),注意-4*(13**3)等于-8788
yy = delta.subs([(x0, 0), (y0, -8788)])
y_tangentLine = delta.subs([(x0, 0), (y0, -8788), (df_sym, k)])
y = yy - fx_sym                  
sol = sp.solve(y, x_sym)
x1 = sol[0]               
x2 = sol[1]

k1 = df_sym.subs(x_sym, x1)              
k2 = df_sym.subs(x_sym, x2)             
tangent1_sym = y_tangentLine.subs(k, k1)
tangent2_sym = y_tangentLine.subs(k, k2)

print("Equation of the tangent line 1 to the curve f(x) :", tangent1_sym)
print("Equation of the tangent line 2 to the curve f(x) :", tangent2_sym)

# 将符号表达式转换为可处理numpy数组的函数
fx_func = sp.lambdify(x_sym, fx_sym, modules=['numpy'])
tangent1_func = sp.lambdify(x_sym, tangent1_sym, modules=['numpy'])
tangent2_func = sp.lambdify(x_sym, tangent2_sym, modules=['numpy'])

# 生成绘图用的x轴数据
x = np.linspace(-500, 500, 50)
fx = fx_func(x)
y1 = tangent1_func(x)
y2 = tangent2_func(x)

# 绘图
plt.plot(x, fx, label='f(x)')
plt.plot(x, y1, label='Tangent 1')
plt.plot(x, y2, label='Tangent 2')
plt.plot(0, -8788, 'rD', label='Point A')
plt.title("Question 1c")
plt.legend()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 17:29:54