如何在pyplot中绘制特定函数以及显示卡方值?

时间:2015-03-25 04:12:23

标签: python matplotlib chi-squared

让我先说一下我是Python /编程的新手。我需要为我正在进行的研究课程这样做,这可能很粗糙。

无论如何,我似乎无法理解如何使用pyplot绘制特定函数(函数在我的代码中的其他地方定义,但检索它们用于绘图是困难的。另外,我如何显示卡方值在每个图表上? 谢谢!

# Chi-square HW 03/25/2015

import numpy as np
from scipy.stats import chi2
from scipy.optimize import minimize
import matplotlib.pyplot as plt

x = np.arange(7)
y = np.array([2, 6, 11, 15, 28, 41, 60])
sigma = np.array([2.1, 0.26, 0.31, 1.55, 0.42, 1.05, 2.1])


# Linear
def lin(vars):
    a,b,c = vars
    lin = a +b*x
    ymod = lin(x,a,b)
    chisq = ((ymod - y)/sigma) **2
    return np.sum(chisq)
    print np.sum(chisq)

# Quadratic
def quad(vars):
    a,b,c = vars
    quad = a + b*x + c*x^2
    ymod = quad(x,a,b,c)
    chisq = ((ymod - y)/sigma) **2
    return np.sum(chisq)
    print np.sum(chisq)

# Exponential
def expn(vars):
    a,b,c = vars
    expn = a * exp(b*x) + c
    ymod = expn(x,a,b,c)
    chisq = ((ymod - y)/sigma) **2
    return np.sum(chisq)
    print np.sum(chisq)

# Power-law
def pwr(vars):
    a,b,c = vars
    pwr = a * x^b + c
    ymod = pwr(x,a,b,c)
    chisq = ((ymod - y)/sigma) **2
    return np.sum(chisq)
    print np.sum(chisq)


#Minimization
def LinRes():
    LinRes = minimize(lin, 0, vars, method='Powell' )
    return LinRes

def QuadRes():
    QuadRes = minimize(quad, 0, vars, method='Powell')
    return QuadRes

def ExpnRes():
    ExpnRes = minimize(expn, 0, vars, method='Powell')
    return ExpnRes

def PwrRes():
    PwrRes = minimize(pwr, 0, vars, method='Powell')
    return PwrRes







#Linear Plot
plt.figure(1)
plt.errorbar(x,y,yerr=sigma, linestyle ='None')
plt.plot(xmod,ymod,'k-')
plt.title('Linear')
plt.show()
plt.savefig('Linear_Plot.png')

#Quadratic Plot
plt.figure(2)
plt.errorbar(x,y,yerr=sigma, linestyle ='None')
plt.plot(xmod,ymod,'k-')
plt.title('Quadratic')
plt.show()
plt.savefig('Quadratic_Plot.png')

#Exponential Plot
plt.figure(3)
plt.errorbar(x,y,yerr=sigma, linestyle ='None')
plt.plot(xmod,ymod,'k-')
plt.title('Exponential')
plt.show()
plt.savefig('Exponential_Plot.png')

#Power-law Plot
plt.figure(4)
plt.errorbar(x,y,yerr=sigma, linestyle ='None')
plt.plot(xmod,ymod,'k-')
plt.title('Power-law')
plt.show()
plt.savefig('Power_Law_Plot.png')

1 个答案:

答案 0 :(得分:0)

请查看下面的代码,它可以纠正您的功能和情节(如果我理解您打算做什么的话)。我没有尝试修复你的最小化尝试,但也许这些评论中的一些可以帮助你。

最明显的纠正错误如下:

  • 目前尚不清楚您是希望函数返回数据模型还是卡方值的总和。建议有一个函数来生成数据模型(ymod),另一个函数来计算卡方和(参见下面代码中的一个例子)。
  • 函数内的print语句必须在return语句之前。否则代码永远不会达到它(此外是一个错误)。
  • plt.plot接收数据点,而不是函数。如果要绘制func(x),则需要提供数据对,例如: plt.plot(x,func(x))。

现在距离更近了。我相信你可以从那里拿走它。

# Chi-square HW 03/25/2015

import numpy as np
import matplotlib.pyplot as plt
from math import exp
from scipy.stats import chi2
from scipy.optimize import minimize

x = np.arange(7)
y = np.array([2, 6, 11, 15, 28, 41, 60])
sigma = np.array([2.1, 0.26, 0.31, 1.55, 0.42, 1.05, 2.1])


# Linear
def lin(vars):
    a,b,c = vars
    return a + b*x

# Quadratic
def quad(vars):
    a,b,c = vars
    return a + b*x + c*x**2

# Exponential
def expn(vars):
    a,b,c = vars
    return a * np.exp(b*x) + c

# Power-law
def pwr(vars):
    a,b,c = vars
    return a * x**b + c


# A generic function for chi-squared values could be the following
def chisq_fun(fun, vars):
    return np.sum(((fun(vars) - y)/sigma) ** 2)





#Minimization
def LinRes():
    LinRes = minimize(lin, 0, vars, method='Powell' )
    return LinRes

def QuadRes():
    QuadRes = minimize(quad, 0, vars, method='Powell')
    return QuadRes

def ExpnRes():
    ExpnRes = minimize(expn, 0, vars, method='Powell')
    return ExpnRes

def PwrRes():
    PwrRes = minimize(pwr, 0, vars, method='Powell')
    return PwrRes




vars = (1.0, 2.0, 3.0)  # (a, b, c)

plt.title('Linear')
plt.subplot(411)
plt.xlabel('x (independent variable)')
plt.ylabel('lin(%s, %s, %s)' % vars)
plt.plot(x, lin(vars), 'o', linewidth=2.0, color='k')
plt.errorbar(x, y, yerr=sigma, linestyle='None')

plt.title('Quadratic')
plt.subplot(412)
plt.xlabel('x (independent variable)')
plt.ylabel('quad(%s, %s, %s)' % vars)
plt.plot(x, quad(vars), 'o', linewidth=2.0, color='k')
plt.errorbar(x, y, yerr=sigma, linestyle='None')

plt.title('Exponential')
plt.subplot(413)
plt.xlabel('x (independent variable)')
plt.ylabel('expn(%s, %s, %s)' % vars)
plt.plot(x, expn(vars), 'o', linewidth=2.0, color='k')
plt.errorbar(x, y, yerr=sigma, linestyle='None')

plt.title('Power-law')
plt.subplot(414)
plt.xlabel('x (independent variable)')
plt.ylabel('pwr(%s, %s, %s)' % vars)
plt.plot(x, pwr(vars), 'o', linewidth=2.0, color='k')
plt.errorbar(x, y, yerr=sigma, linestyle='None')

plt.show()

(a, b, c) = vars
print("Chi-squared sum for lin(%s, %s, %s) is %f" % (a, b, c, chisq_fun(lin, vars)))
print("Chi-squared sum for quad(%s, %s, %s) is %f" % (a, b, c, chisq_fun(quad, vars)))
print("Chi-squared sum for expn(%s, %s, %s) is %f" % (a, b, c, chisq_fun(expn, vars)))
print("Chi-squared sum for pwr(%s, %s, %s) is %f" % (a, b, c, chisq_fun(pwr, vars)))