如何按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
相关产品推荐
相关产品推荐

