1

I using sympy and matplotlib to draw a graph, but I have an error. I use sympy to solve the equation, and use matplotlib to draw graphs

What am I doing wrong?

Here is the code:

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()

Error message:

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,)
Mel
  • 5,837
  • 10
  • 37
  • 42
Ld Hòa
  • 13
  • 3
  • To plot with matplotlib, x and y needs to be list (or numpy.array). Here `y` is the sympy equation, that's why you get an error – Mel May 09 '17 at 06:55

1 Answers1

0

OK, there are a few thing going wrong here.

First, the variable x: After the imports you define it as a sympy variable which is then used in your expressions. But then you overload it as an array containing the x values for plotting. So you probably want to change that to

x_vals = np.arange(0, 5, 1)

Second, as mentioned in the comments above, y has to be a list or numpy array. To generate that you would have to do something like

y = np.empty(x_vals.shape)
for i in range(len(x_vals)):
    y[i] = pttq.subs(x,x_vals[i]).evalf()

Finally, you probably want to have a smaller step size in x for the plot:

x_vals = np.arange(0, 5, .1)
obachtos
  • 977
  • 1
  • 12
  • 30