Use matplotlib to plot the functions $y = x^3 + 3x^2 - x + 0.3\ $ and $y = \sin x$

1.1k Views Asked by At

I'm new to Python coding and wondered if someone could give me the coding to plot these two graphs on the same program.

This is what I have so far, exactly as typed on Python, however I know that parts are incorrect.

from matplotlib import pyplot as plt

x = [float(i)/100 for i in range(0,101)]
y = [sin(x)]

plt.plot(x,y)
1

There are 1 best solutions below

7
On BEST ANSWER

First, you need a larger range for $x$ to see a nice sinusoid, say from $0$ to $2\pi$. Second, specify $y$ as a list comprehension, too:

from matplotlib import pyplot as plt
import math

x = [float(i)/100 for i in range(0, 628)]
y = [math.sin(z) for z in x]

plt.plot(x,y)

enter image description here


If you want to plot both graphs one over the other (what isn't generally a good idea because those 2 function are so different, that in the default settings the sine function will appear as to coincide with the x-axis), the code may be as follows (I extended the range for $x$, and set limits for $y$-axes):

from matplotlib import pyplot as plt
import math

BOUND = 1000

x = [float(i)/100 for i in range(-BOUND, +BOUND)]
y = [math.sin(z) for z in x]
w = [z**3 + 3*z**2 - z + 0.3 for z in x]


plt.ylim(-7,+7)
plt.plot(x, y)
plt.plot(x, w)

enter image description here