如何用seaborn.lmplot绘制行求和后的支出与收入散点回归图?
解决Seaborn lmplot的行求和与绘图问题
代码错误分析
你当前的代码存在三个核心问题:
- 错误使用
sum():直接对列名字符串列表调用sum(),会把字符串拼接而非计算数值求和,完全不符合需求。 - 误用
groupby():这里不需要分组聚合,而是要对每行的指定列进行求和,groupby()是用于分组统计的工具,不适用此场景。 - lmplot参数错误:
sns.lmplot的x和y参数需要传入数据框中已存在的列名,而非变量对象。
正确实现步骤
要实现需求,只需在原数据框中新增两个行求和后的列,再传入lmplot即可:
- 计算
Private Sector Expenditure和Public Sector Expenditure的行和,生成Total_Expenditure列 - 计算指定5个收入列的行和,生成
Total_Revenue列 - 用这两个新列作为x、y轴绘制lmplot
完整代码示例
import seaborn as sns import pandas as pd # 假设df_final是你合并后的完整数据集 # 生成总支出列 df_final['Total_Expenditure'] = df_final[['Private Sector Expenditure', 'Public Sector Expenditure']].sum(axis=1) # 生成总收入列 revenue_cols = ['Content Services Revenue', 'Hardware Revenue', 'IT Services Revenue', 'Software Revenue', 'Telecommunication Services Revenue'] df_final['Total_Revenue'] = df_final[revenue_cols].sum(axis=1) # 绘制lmplot sns.lmplot(data=df_final, x='Total_Expenditure', y='Total_Revenue')
补充说明
axis=1参数指定按行求和(默认axis=0是按列求和)- 新列会直接添加到原数据框中,后续绘图时直接传入列名字符串即可
- 如果需要保留原数据框不被修改,可以使用
df_final.copy()创建副本后再操作
内容的提问来源于stack exchange,提问作者Lim Ze Kai
相关产品推荐
相关产品推荐

