2017-05-09 93 views
1

我使用sympy和matplotlib繪製圖形,但出現錯誤。 我使用sympy來解決方程,並使用matplotlib繪製圖形Sympy-matplotlib:x和y必須具有相同的第一維

我在做什麼錯?

下面是代碼:

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

要使用matplotlib,x和y的需要繪製列表(或numpy.array)。這裏'y'是sympy等式,這就是爲什麼你得到一個錯誤 – Mel

回答

0

OK,有走錯了這裏幾件事。

首先,變量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) 
+0

謝謝,我修正了錯誤 –

相關問題