You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中对用户进行二分类并绘制带回归线的分类图?

基于value列的用户二分类及带回归线的可视化

1. 导入所需库

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

2. 初始化DataFrame

df = pd.DataFrame({
    'user': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    'x': [1.6, 0.5, 0.4, 4.2, 2.6, 1, 1.6, 2.1, 2, 1.2],
    'y': [1.2, 0.3, 0.7, 1.2, 3, 3, 3, 3, 3, 3],
    'value': [2.8, 0.8, 1.1, 5.4, 5.6, 4, 4.6, 5.1, 5, 4.2]
})

3. 基于value列进行二分类

这里选择中位数作为分类阈值,将用户分为"低value组"和"高value组":

# 计算value列的中位数
threshold = df['value'].median()
# 新增分类列
df['category'] = df['value'].apply(lambda v: '低value组' if v <= threshold else '高value组')

如果需要用数值标记分类(0/1),可以用:

df['category_num'] = df['value'].apply(lambda v: 0 if v <= threshold else 1)

4. 绘制带回归线的分类结果图

方案1:x-y散点+分类回归线

用seaborn的lmplot直接绘制散点图,同时按分类区分颜色并添加回归线:

# 设置绘图风格
sns.set_style("whitegrid")

# 绘制图形
g = sns.lmplot(
    data=df,
    x='x',
    y='y',
    hue='category',
    markers=['o', 's'],  # 不同分类用不同标记
    fit_reg=True,  # 开启回归线
    height=6,
    aspect=1.2
)

# 添加标题和标签
g.set(title='基于value分类的用户x-y分布及回归线', xlabel='x值', ylabel='y值')

# 显示图形
plt.show()

方案2:用户ID-value散点+整体回归线

如果需要展示用户ID与value的关系,同时添加整体回归线:

plt.figure(figsize=(10, 6))
# 绘制分类散点
sns.scatterplot(data=df, x='user', y='value', hue='category', s=100)
# 添加整体回归线
sns.regplot(data=df, x='user', y='value', scatter=False, color='gray')

# 配置图形元素
plt.title('用户value值分布及回归线')
plt.xlabel('用户ID')
plt.ylabel('value值')
plt.legend(title='分类')

plt.show()

内容的提问来源于stack exchange,提问作者alxander21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 16:32:19