在python中为多个图包含唯一的最佳拟合线和r2值

问题描述 投票:0回答:2

我有一个带有多个散点图的图形,当我尝试包含一条最佳拟合线时,它为每个图形提供了相同的线条。这就是现在的样子:

enter image description here

但我希望该线对每个图中的数据点都是唯一的。

这是我到目前为止的代码。我不会包含输入数据的代码,因为它很多,我很确定问题是在for循环中。

import pandas as pd
import matplotlib.pyplot as plt
for i in range(len(uniq)):
    plt.subplot(6,6,i+1)
    indx = dat['year'] == uniq[i]
    plt.scatter(x[indx], y[indx], s=15, color=scalarMap.to_rgba(i), label=uniq[i])
    m, b = np.polyfit(x, y, 1)
    plt.plot(x, m*x + b, '-')

编辑问题:

如何打印最适合的线条的r2值?到目前为止,我有:

from scipy import stats
def rsquared(x, y):
     """ Return R^2 where x and y are array-like."""
    slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x, y)
    return r_value**2

for i in range(len(uniq)):
    plt.subplot(6,6,i+1)
    indx = dat['year'] == uniq[i]
    plt.scatter(x[indx], y[indx], s=15, color=scalarMap.to_rgba(i), label=uniq[i])
    plt.legend(prop={'size':5})
    plt.xticks(size = 10)
    plt.yticks(size = 10)
    m, b = np.polyfit(x[indx], y[indx], 1)
    plt.plot(x, m*x + b, '-')
    slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x[indx], y[indx])
    print("r-squared:", r_value**2)

如果我可以在最佳拟合线旁边打印r2值,那也很棒。

python pandas matplotlib statistics
2个回答
1
投票

对于新编辑,要注释绘图,只需使用matplotlibannotate

plt.annotate('Corr. coef = %.3f' % r_value**2, (0.8, 0.2), xycoords='axes fraction', ha='center', va='center', size=10)

annotated graph


0
投票

问题由@gereleth解决

for i in range(len(uniq)):
    plt.subplot(6,6,i+1)
    indx = dat['year'] == uniq[i]
    plt.scatter(x[indx], y[indx], s=15, color=scalarMap.to_rgba(i), label=uniq[i])
    plt.legend(prop={'size':5})
    plt.xticks(size = 10)
    plt.yticks(size = 10)
    m, b = np.polyfit(x[indx], y[indx], 1)
    plt.plot(x, m*x + b, '-')

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.