-1

I want to plot any mathematical function such as y=x**2 or y=sin(x)/x (anything basically). The problem is, I can only plot functions defined in numpy such as np.sin, np.cos or np.tan. The entire point here is how to avoid "hard coding" vectors and then plot those.

How can I plot arbitrary functions? Here is what I have so far:

import matplotlib.pyplot as plt
import numpy as np

#Let a be starting point on x
#Let b be end point on x
#Let f be the function you wish to plot

CornflowerBlue="6495ed"

def plotf(a,b,f):
    
    x=np.linspace(a,b,num=b*10)
    y=np.array([])
    
    for i in range (len(x)):
       
        y = np.append(y,f(x[i]))
        
    plt.grid(True)
    plt.plot(x,y,color="CornflowerBlue")
    plt.axhline(y=0,color="black")
    return 
4
  • I can only plot functions defined in numpy such as np.sin, np.cos or np.tan. What do you mean by that? If i use plotf(-5, 5, lambda x: x**2 + 1) and then plt.show() it correctly renders a function that is not defined in numpy. Commented Dec 20, 2020 at 23:19
  • Thank you! The trick was to use lambda Commented Dec 20, 2020 at 23:47
  • 1
    def f(x): return x**2 + 1 with plt.show() and plotf(-5, 5, f) works the same, I still don't get what your question is. Commented Dec 20, 2020 at 23:49
  • 1
    just a tip: if you're using numpy arrays, you don't need to loop through them. In other words, y = x**2 + 1 is all you need to do Commented Dec 21, 2020 at 0:02

1 Answer 1

1

You could try sympy as it should allow you to play with a variety of mathematical functions without explicitly hardcoding them:

from sympy import *

def plotf(a,b,f):
    plot(f, xlim = (a,b)) 

plotf(-10, 10, "sin(x)/x") # or plotf(0, 2, "x**2"), or (almost) whatever

See for details https://docs.sympy.org/latest/modules/plotting.html!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.