我使用sympy和matplotlib绘制图形,但是我有一个错误。 我使用sympy来解决方程式,并使用matplotlib绘制图形
我做错了什么?
以下是代码:
import numpy as np
import sympy
import math
from mpmath import *
from sympy import *
import matplotlib.pyplot as plt
x= symbols('x')
f, g, h = symbols('f g h', cls=Function)
A, C1, C2 = symbols('A C1 C2')
input = C1 * sin(5*x) + C2 * cos(5*x) + x/25
ex1 = input.subs({x:0})
ex2 = input.subs({x:4})
kq = solve((ex1, ex2), C1, C2)
pttq = input.subs({C1:kq[C1], C2: kq[C2]})
print(pttq)
x = np.arange(0, 5, 1)
y = pttq
fig, ax = plt.subplots()
plt.xlabel('(m)')
plt.ylabel('(KN)')
plt.title('NEO')
plt.plot(x, y)
plt.show()
错误讯息:
Traceback (most recent call last):
File "\Text", line 31, in <module>
File "C:\Blender\2.78\python\lib\site-packages\matplotlib\pyplot.py", line 3318, in plot
ret = ax.plot(*args, **kwargs)
File "C:\Blender\2.78\python\lib\site-packages\matplotlib\__init__.py", line 1892, in inner
return func(ax, *args, **kwargs)
File "C:\Blender\2.78\python\lib\site-packages\matplotlib\axes\_axes.py", line 1406, in plot
for line in self._get_lines(*args, **kwargs):
File "C:\Blender\2.78\python\lib\site-packages\matplotlib\axes\_base.py", line 407, in _grab_next_args
for seg in self._plot_args(remaining, kwargs):
File "C:\Blender\2.78\python\lib\site-packages\matplotlib\axes\_base.py", line 385, in _plot_args
x, y = self._xy_from_xy(x, y)
File "C:\Blender\2.78\python\lib\site-packages\matplotlib\axes\_base.py", line 244, in _xy_from_xy
"have shapes {} and {}".format(x.shape, y.shape))
ValueError: x and y must have same first dimension, but have shapes (5,) and (1,)
答案 0 :(得分:0)
好的,这里有一些问题。
首先,变量x
:
导入后,将其定义为sympy变量,然后在表达式中使用。但是你将它作为包含绘图的x值的数组重载。所以你可能想把它改成
x_vals = np.arange(0, 5, 1)
其次,如上面的评论所述,y
必须是列表或numpy数组。要生成它,您必须执行类似
y = np.empty(x_vals.shape)
for i in range(len(x_vals)):
y[i] = pttq.subs(x,x_vals[i]).evalf()
最后,您可能希望在x中使用较小的步长:
x_vals = np.arange(0, 5, .1)