-1

I'm trying to make a simple plotting function plot2d,

def plot2d(xmin,xmax,func): 

    x=np.linspace(xmin, xmax, num=50)    

    plt.plot(x,func)
    plt.show()

The idea is you input the variable 'func' in terms of x, like x**2.

edit* Here's the error:

>>> plot2d(-10,10, x**2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

edit** I think the issue was that when you first call the function the linspace x hasn't be created yet. This worked:

import numpy as np
import matplotlib.pyplot as plt

def plot2d(xmin,xmax): 
x=np.linspace(xmin, xmax, num=50)    

func=input('Define fucntion: ')
plt.plot(x,func)
plt.show()
user3556814
  • 21
  • 1
  • 4

2 Answers2

4

You might want to learn about lambda. Change your code a bit would suffice:

import numpy as np
import matplotlib.pyplot as plt

def plot2d(xmin,xmax,func): 

    x=np.linspace(xmin, xmax, num=50)    

    plt.plot(x,func(x)) #func -> func(x)
    plt.show()

#pass a unnamed lambda as a param: 
plot2d(-10, 10, lambda x: x*x)
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
0
from pylab import *

def plot2d(xmin, xmax, func):
    x=np.linspace(xmin,xmax,num=50)
    y=func(x)
    plot(x,y)
    show()

def func(x):
    y=x**2
    return y

plot2d(0,10,func)

Result:

enter image description here

Ashoka Lella
  • 6,631
  • 1
  • 30
  • 39
  • My hope was to be able define any functions. TBH I was going for something resembling mathematicas plot function. – user3556814 Apr 21 '14 at 14:17
  • @user3556814, Taking function from user as input deviates from the scope of this thread. You might want to refer to http://stackoverflow.com/questions/7719466/how-to-convert-a-string-to-a-function-in-python – Ashoka Lella Apr 21 '14 at 14:26