0

With pyplot you can plot a function with

x = np.linspace(-10, 10, num=100) #start x, end x, number of points on line

fx = []
for i in range(len(x)):
  fx.append(-2*x[i]**3 - 35*x[i]**2 + 39*x[i] + 70) #creates function f(x)

plt.plot(x, fx) #plots function f(x)
plt.grid() #adds grid
plt.axvline() #adds line at x=0
plt.axhline() #adds line at y=0  
plt.show() #actually makes graph appear

this will plot the function f(x) = -2x3-35x2+39x+70, but how do you make it so it will graph a function that you input?

I've tried just feeding in a string that follows the same format as what it is normally with

foo = "4*x[i]**3"
fx.append(foo)

but that just gives me this pyplot plot where the y axis is labeled "4*x[i]**3" with no actual graph plotted

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Lain
  • 16
  • 4
  • I just ran the code from the question(add imports) `import numpy as np from matplotlib import pyplot as plt` and got the following output (which I'm guessing is what's expected) https://i.stack.imgur.com/aR2ub.png ran using Python 3.11.4 and matplotlib-3.7.2 – Samuel Gottipalli Aug 30 '23 at 17:39
  • 1
    @SamuelGottipalli you have misunderstood the question. The OP wants to be able to evaluate a function input as a string (e.g. `foo = "4*x[i]**3"`). The question _this will plot the function f(x) = -2x3-35x2+39x+70, but how do you make it so it will graph a function that you input?_ – Trenton McKinney Aug 30 '23 at 17:40
  • 1
    @TrentonMcKinney lol.. totally misread it! Thank you! – Samuel Gottipalli Aug 30 '23 at 17:43
  • 1
    As stated in the duplicate, `eval`. But `eval` can be problematic. See [code and plot](https://i.stack.imgur.com/mohVe.png) – Trenton McKinney Aug 30 '23 at 17:43

0 Answers0