我已经为回归线编写了这段代码,但该线没有显示:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
data=pd.read_csv("NHANES.csv")
correlation = data['BMI'].corr(data['Waist'])
print(f"Korrelationskoeffizient: {correlation}")
slope, intercept, r_value, p_value, std_err = stats.linregress(data['BMI'], data['Waist'])
regression_line = slope * data['BMI'] + intercept
plt.scatter(data['BMI'], data['Waist'], label='Streudiagramm')
plt.plot(data['BMI'], regression_line, color='red', label='Regressionsgerade')
plt.xlabel('BMI')
plt.ylabel('Waist')
plt.legend()
plt.show()
相关性为0.9
我只有散点图,没有线条
检查截距的变量类型。这是对我有用的代码:
import matplotlib.pyplot as plt
import numpy as np
price = [2.50, 1.23, 4.02, 3.25, 5.00, 4.40]
sales_per_day = [34, 62, 49, 22, 13, 19]
slope, intercept = np.polyfit(price, sales_per_day, 1)
regression_line = [slope * x + intercept for x in price]
print(type(regression_line) # this is list in this example
plt.scatter(price, sales_per_day, label='Scatter Plot')
plt.plot(price, regression_line, color='red', label='Regression Line')
plt.xlabel('Price')
plt.ylabel('Sales per Day')
plt.legend()
plt.show()