Python等高线图在尝试绘制导入的d时出现错误

2024-04-19 11:21:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我的任务是获取一组模拟数据,绘制可信区域的等高线图,然后测试后验数据。但是,每当我更改绘制等高线图所依据的值时,物理等高线图都会更改,因为它只应是更改的图形轴。我看不到我的代码中有任何错误,用Matlab编写的类似代码运行良好

代码如下:

##Necessary Imports
import numpy as np
import numpy.random as nprd
import matplotlib.pyplot as plt
import pandas as pd

##Import and specify X and Y data 

datax = pd.read_excel(r'\Users\user\Documents\Med Phys STP\MSc Year\ADA\MDC\MDC1X.xlsx')
x1=[]
x1.append(datax['x'])
xT = np.multiply(x1,1)
x = np.transpose(xT)
datay = pd.read_excel(r'\Users\user\Documents\Med Phys STP\MSc Year\ADA\MDC\MDC1Y.xlsx')
y1=[]
y1.append(datay['y'])

yT = np.multiply(y1,1)
y= np.transpose(yT)
##Define sigma and range and nunmber of trial parameters for a and b


a = np.linspace(4,4.8,100)
b = np.linspace(1.9,2.2,100)

sumx = np.sum(x)
sumy = np.sum (y)
x2 = x**2
sumx2 = np.sum(x2)
y2 = y**2
xy = x*y
sumxy = np.sum(x*y)

## Calculating Least squares value A
a1 =(sumy*sumx2)-(sumxy*sumx)
a2 = (5*sumx2)-(sumx*sumx)
a_ls = a1/a2
print (a_ls)




## Calculating Least Squares value B
b_ls = (5*sumxy-sumx*sumy)/(5*sumx2-sumx*sumx)

#print (a_ls)
print (b_ls)

##Calculating the Y pred values
Ypred = a_ls + np.multiply(b_ls,x)

##Calculating the difference between observed and predicted data 
Ei = np.subtract(y,Ypred)
print (Ei)
##calculating sigma with 998 degrees of freedom 
#Sigma = np.sqrt(np.sum(np.power(Ei,2))/998)
#print (Sigma)
Sigma = 0.8
##Calculate chi-squared for trial parameters
chisq = np.zeros((len(a),len(b)))

for i in range(0,len(a)):
    for j in range(0,len(b)):
        for k in range(0,999):
            chisq[i,j] = chisq[i,j] + ((y[k]-(a[i]+(b[j]*x[k])))/Sigma)**2


##Calculate delchisq
chisqmin = np.amin(chisq)

delchisq = chisq - chisqmin
##Create and plot contours
cont = [2.3, 6.7, 11.8]
A,B = np.meshgrid(a,b)
plt.contour(a,b,delchisq,cont)

任何帮助都将不胜感激。我很乐意澄清任何人可能提出的任何问题

TL;DR,等高线图形状随a和b的值而变化,但不应如此


Tags: andimportforasnprangelssigma