如何用Python为父子身高数据集绘制线性回归线?
如何在父子身高散点图中添加线性回归线?
要在现有散点图上添加线性回归线,Seaborn提供了两种简单的实现方式,以下是针对你的代码的修改方案:
完整修改后的代码
# Author: Evan Gertis # Date 11/15 # program: linear regression import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') # 读取数据集 df = pd.read_csv('father_son_data.csv') # 可选:重命名列名以简化代码(原列名包含空格和括号) df.columns = ['Father_Height', 'Son_Height'] logging.info(f"{df}") # 方法1:直接用regplot生成带回归线的散点图(推荐) # 默认会绘制散点、线性回归线,以及95%置信区间(可通过ci=None关闭) plot = sns.regplot(data=df, x='Father_Height', y='Son_Height', label='Son Height') # 方法2:先自定义散点图,再叠加回归线 # 适合需要单独调整散点样式的场景 # plot = sns.scatterplot(data=df, x='Father_Height', y='Son_Height', label='Son Height', color='blue') # # scatter=False表示只画回归线,ax=plot指定在同一个坐标轴上绘制 # sns.regplot(data=df, x='Father_Height', y='Son_Height', scatter=False, color='red', ax=plot) # 添加图表标注 plt.title('Father vs Son Height with Linear Regression Line') plt.xlabel('Father Height (in)') plt.ylabel('Son Height (in)') plt.legend() # 保存图片 fig = plot.get_figure() fig.savefig("Father_Son.png")
关键说明
- 移除不必要的循环:你的数据集只有一组父子身高变量,不需要
chunker函数和循环遍历列组,直接指定列名即可。 - 使用
regplot函数:Seaborn的regplot是专门用于展示变量间线性回归关系的工具,默认会自动计算并绘制回归线,同时支持自定义置信区间、线条样式等。 - 列名重命名(可选):原数据集的列名包含空格和特殊字符,重命名后能让代码更易读、避免潜在的语法问题。
内容的提问来源于stack exchange,提问作者Evan Gertis
相关产品推荐
相关产品推荐

