0

If I have a function

def function(self, x, A, B)
   ......

How can I plot a continuous graph of it over a range of say x=[0,150000] (A/B are constants and can be changed on each call).

Even discrete values is fine. However it is inefficient to make a list of all function values then plot each one?

1
  • 1
    Your question is not very clear here. Plotting is always discrete. There are just way too many numbers in a closed interval of real numbers :) Commented Aug 11, 2015 at 8:26

1 Answer 1

3

I'm assuming you mean the function is going to be some kind of mathematical function, for example:

import math
def function(x, A, B):
    return math.exp(A*x) * math.sin(B*x)

Then I would define variables for the number of points to plot, and the x range, and then create lists using map, as below.

import matplotlib.pyplot as plt
points = 1e4 #Number of points
xmin, xmax = -1, 5
xlist = map(lambda x: float(xmax - xmin)*x/points, range(points+1))
ylist = map(lambda y: function(y, -1, 5), xlist)
plt.plot(xlist, ylist)
plt.show()
Sign up to request clarification or add additional context in comments.

3 Comments

I am getting error- >>> xlist = map(lambda x: float(xmax - xmin)*x/points, range(points+1)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'float' object cannot be interpreted as an integer
@Ankit Make sure the variable points is an integer (there can only be an integer number of points). The error comes from calling range with a non-integer argument. This answer was written for Python 2 where 1e4 is an integer, whereas it is a float in Python 3.
Instead of xlist = map(lambda x: float(xmax - xmin)*x/points, range(points+1)) you may wish to use NumPy's linspace function: import numpy as np and then xlist = np.linspace(xmin, xmax, points)

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.