Tuesday, April 26, 2011

How to plot a function using matplotlib

We will see how to evaluate a function using numpy and how to plot the result.
import pylab
import numpy

x = numpy.linspace(-15,15,100) # 100 linearly spaced numbers
y = numpy.sin(x)/x # computing the values of sin(x)/x

# compose plot
pylab.plot(x,y) # sin(x)/x
pylab.plot(x,y,'co') # same function with cyan dots
pylab.plot(x,2*y,x,3*y) # 2*sin(x)/x and 3*sin(x)/x
pylab.show() # show the plot
The command pylab.show() will open a window with the following plot:
Image

12 comments:

  1. Image
  2. Image
  3. Image
  4. Image

    Very good info, thanks!!!

    ReplyDelete
  5. Image

    How to realize it without numpy?!

    ReplyDelete
    Replies
    1. Image

      It's easy, you just need to generate the vectors x and y in another way. For example, x = [a*1.0 for a in range(0,10)] and y = [sin(xx) for xx in x].

      Delete
  6. Image

    Is it possible to plot a function and not just an equation?

    ReplyDelete
  7. Image
  8. Image

    How to plot something like the following equation?

    (x+y−2)^2

    ReplyDelete
    Replies
    1. Image

      Hi Divij, here's an example that can hep you: https://glowingpython.blogspot.co.uk/2012/01/how-to-plot-two-variable-functions-with.html

      Delete
  9. Image

    Thanks for the code, that helped a lot and gave some idea about what to use etc. But what I'm wondering is , do we really need to use only standart functions that have defined by Numpy? Or can we define a function ourselves and use it in numpy function too ?
    Thanks anyways, good code

    ReplyDelete
  10. Image

    Great but it's easy...

    ReplyDelete

Note: Only a member of this blog may post a comment.