Python 在1个图形中绘制2个数据集+;MATPLOTLIB中的线性回归

Python 在1个图形中绘制2个数据集+;MATPLOTLIB中的线性回归,python,matplotlib,linear-regression,Python,Matplotlib,Linear Regression,我是Python新手,有任何编程背景。。 我试图为相同的x数据集绘制两个y数据集,使用scipy对其进行线性回归,得到R^2值。到目前为止,我就是这样做到的: import matplotlib import matplotlib.pyplot as pl from scipy import stats #first order '''sin(Δθ)''' y1 = [-0.040422445,-0.056402365,-0.060758191] #second order '''sin(Δ

我是Python新手,有任何编程背景。。 我试图为相同的x数据集绘制两个y数据集,使用scipy对其进行线性回归,得到R^2值。到目前为止,我就是这样做到的:

import matplotlib
import matplotlib.pyplot as pl

from scipy import stats

#first order
'''sin(Δθ)'''
y1 = [-0.040422445,-0.056402365,-0.060758191]
#second order
'''sin(Δθ)'''
y2 = [-0.083967708, -0.107420964, -0.117248521]
''''λ, theo (nm)'''
x= [404.66, 546.07, 579.06]
pl.title('Angular displacements vs. Theoretical wavelength')
pl.xlabel('theoretical λ (in nm)')
pl.y1label('sin(Δθ) of 1st order images')
pl.y2label('sin(Δθ) of 2nd order images')
plot1 = pl.plot(x, y1, 'r')
plot2 = pl.plot(x, y2, 'b')
pl.legend([plot1, plot2], ('1st order images', '2nd order images'), 'best', numpoints=1)
slope1, intercept1, r_value1, p_value1, std_err1 = stats.linregress(x,y1)
slope2, intercept2, r_value2, p_value2, std_err2 = stats.linregress(x,y2)
print "r-squared:", r_value1**2
print "r-squared:", r_value2**2
pl.show()
…我没有得到任何绘图,我得到了错误: “UnicodeDecodeError:'ascii'编解码器无法解码位置12:序号不在范围(128)中的字节0xce”


我不明白。有人能帮我告诉我我的代码出了什么问题吗?谢谢你uu

此代码中有多个错误

  • 在这里,您不能简单地在打印标签和标题中键入希腊字母 这就是你如何做到的:

    pl.xlabel(r'theoretical $\lambda$ (in nm)')
    
  • y1label
    y2label
    不是
    pl
    模块的对象

  • 在Python中,
    #blah blah
    不同于
    ''blah blah'
    。第一个是注释,第二个是表达式。您可以将第二个分配给变量(
    a=''blah blah'
    ),但不能将第一个分配给变量:
    a=#blah blah
    生成语法错误

  • 下面是一个应该有效的代码:

    import matplotlib
    import matplotlib.pyplot as pl
    from scipy import stats
    
    y1 = [-0.040422445,-0.056402365,-0.060758191]
    y2 = [-0.083967708, -0.107420964, -0.117248521]
    x= [404.66, 546.07, 579.06]
    
    pl.title('Angular displacements vs. Theoretical wavelength')
    pl.xlabel(r'theoretical $\lambda$ (in nm)')
    pl.ylabel(r'sin($\Delta\theta$)')
    
    y1label = '1st order images'
    y2label = '2nd order images'
    
    plot1 = pl.plot(x, y1, 'r', label=y1label)
    plot2 = pl.plot(x, y2, 'b', label=y2label)
    
    pl.legend()
    
    slope1, intercept1, r_value1, p_value1, std_err1 = stats.linregress(x,y1)
    slope2, intercept2, r_value2, p_value2, std_err2 = stats.linregress(x,y2)
    print "r-squared:", r_value1**2
    print "r-squared:", r_value2**2
    
    pl.show()
    

    哦,非常感谢!但是,我是否可以将sin($\Delta\theta$)作为y轴的标签,然后将序列标签更改为“一阶图像”和“二阶图像”作为另一个?此外,我是否可以将计算出的r^2值也包括在图形中?(比如你怎么能在excel里?呵呵)不知道你的意思。如果只想添加文本,可以将r^2值添加到图例中。或者可以使用注释()