【问题标题】:Plotting 2 data sets in 1 graph + linear regression in MATPLOTLIB在 1 个图形中绘制 2 个数据集 + MATPLOTLIB 中的线性回归
【发布时间】:2017-01-18 23:56:51
【问题描述】:

我是 Python 新手,有任何编程背景。 我正在尝试为相同的 x 数据集绘制 2 个 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 的字节 0xce:序数不在范围内 (128)”

我不明白。有人可以帮忙告诉我我的代码有什么问题吗?谢谢你哦

【问题讨论】:

    标签: python matplotlib linear-regression


    【解决方案1】:

    这段代码有多个错误。

    1. 你不能简单地在情节标签和标题中输入希腊字母,这里 你是怎么做到的:

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

    3. 在 Python 中,# blah blah'''blah blah''' 不同。第一个是注释,第二个是表达式。您可以将第二个分配给变量 (a = '''blah blah'''),但不能将第一个分配给变量:a = # blah blah 会产生 SyntaxError。

    这是一个应该可以工作的代码:

    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 值添加到图例中。或者您可以使用注释 (matplotlib.org/1.5.1/users/annotations_intro.html)
    猜你喜欢
    • 2019-10-10
    • 1970-01-01
    • 2019-06-16
    • 2022-01-15
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    相关资源
    最近更新 更多