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

如何按year列分组绘制DataFrame中number与points列的关系图

最简绘图实现方案

优先选择seaborn实现,代码量最低,无需手动调整图例映射,核心绘图仅需1行代码:

  • 前置准备:未安装依赖的话先执行pip install pandas seaborn matplotlib
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame({'year': [1,2,3],
                    'number' :[4,5,6],
                    'points': [10000,20000,30000]})

# 指定数据源、xy轴对应字段、按year分组着色自动生成图例
sns.scatterplot(data=df, x="number", y="points", hue="year")
plt.show()

如果不想额外安装seaborn,用pandas搭配原生matplotlib也可实现,逻辑是按year分组遍历绘制散点:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'year': [1,2,3],
                    'number' :[4,5,6],
                    'points': [10000,20000,30000]})

for year, group in df.groupby("year"):
    plt.scatter(group["number"], group["points"], label=year)

plt.xlabel("number")
plt.ylabel("points")
plt.legend(title="year")
plt.show()

两种方案输出的图表均满足需求:x轴映射number字段、y轴映射points字段,图例按year字段值区分不同数据点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 06:36:27