2

So I'd like to plot simple gamma function, but I have some problems. My code is:

#!/usr/bin/env python
# -*- coding: cp1250 -*-
#import math
from scipy.special import *
#from scitools.std import *
from pylab import *

def f1(x):
    return gamma(x)


x = linspace(-6, 6, 512)
y1 = f1(x)

# Matlab-style syntax:
plot(x, y1)

xlabel('x')
ylabel('y')
legend(r'$\Gamma(x)$')
grid(True)

show()

I tried importing the gamma function from math, and from scipy.special but I get the following error:

Traceback (most recent call last): File "D:/faxstuff/3.godina/kvantna/plotgamma.py", line 13, in y1 = f1(x) File "D:/faxstuff/3.godina/kvantna/plotgamma.py", line 9, in f1 return gamma(x) File "mtrand.pyx", line 1599, in mtrand.RandomState.gamma (numpy\random\mtrand\mtrand.c:8389) ValueError: shape <= 0

How to do it? This should be easy, but I seem to fail :(

3
  • Please post the exact error messages. Commented Apr 16, 2011 at 9:34
  • Traceback (most recent call last): File "D:/faxstuff/3.godina/kvantna/plotgamma.py", line 13, in <module> y1 = f1(x) File "D:/faxstuff/3.godina/kvantna/plotgamma.py", line 9, in f1 return gamma(x) File "mtrand.pyx", line 1599, in mtrand.RandomState.gamma (numpy\random\mtrand\mtrand.c:8389) ValueError: shape <= 0 Commented Apr 16, 2011 at 10:30
  • 1
    This is a good example of why import * is not recommended. Commented Nov 24, 2016 at 0:36

2 Answers 2

3

One of the modules (pylab, I think) is shadowing the gamma function by the gamma random variable function. This works, but I had to turn off the call to legend (I'm not sure why, yet).

from scipy.special import gamma as Gamma
#from scitools.std import *
from pylab import *

def f1(x):
    return Gamma(x)


x = linspace(-6, 6, 512)
y1 = f1(x)
gca().set_autoscale_on(False)

# Matlab-style syntax:
plot(x, y1)

xlabel('x')
ylabel('y')
# legend(r'$\Gamma(x)$')
axis([-6, 6, -100, 100])
grid(True)

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

2 Comments

Needed to change it to: legend([r'$\Gamma(x)$'])
This is a perfect illustration of why "from foo import *" is not recommended.
2

Try this in a Sage notebook:

# Simple example demonstrating how to interact with matplotlib directly.
# Comment plt.clf() to get the plots overlay in each update.

from scipy import stats
import numpy as np
import matplotlib.pyplot as plt

@interact
def plot_gamma(a=(1,(1,10)), loc=(0,(0,10)), scale=(1,(1,10))):
    rv = stats.gamma(a, loc, scale)
    x = np.linspace(-1,20,1000)
    plt.plot(x,rv.pdf(x))
    plt.grid(True)
    plt.savefig('plt.png')
    plt.clf()

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.