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

如何基于pandas分组列值绘制带不同标记的matplotlib散点图

问题原因

matplotlib的scatter方法的marker参数仅支持传入单个标记样式,不支持直接传入包含多个样式的Series对象,因此之前的写法会触发类型错误。

你提到的「按group列分组后分别调用scatter」的思路本身是合理的,也不是逐行遍历,仅需要按分组数调用对应次数的绘图方法,性能和可读性都很好,实现代码如下:

方案1:原生Matplotlib实现

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

colors = ['r','g','b','y']
markers = ['o', '^', 's', 'P']

# 构造测试数据
df = pd.DataFrame()
df["index"] = list(range(100))
df["data"] = np.random.randint(100, size=100)
df["group"] = np.random.randint(4, size=100)

plt.figure()
# 按group分组遍历,仅循环4次,不是逐行遍历
for group_id, group_df in df.groupby('group'):
    plt.scatter(x=group_df["index"], y=group_df["data"], 
                c=colors[group_id], marker=markers[group_id], 
                label=f'分组{group_id}')
plt.legend()
plt.show()

方案2:Seaborn极简实现

如果可以引入第三方绘图库,使用seaborn的scatterplot可以一行代码实现需求,不需要手动写循环:

import seaborn as sns

sns.scatterplot(data=df, x='index', y='data', 
                hue='group', style='group', 
                palette=colors, markers=markers)
plt.show()

参数说明:

  • hue参数控制分组对应的颜色
  • style参数控制分组对应的marker样式
  • palette传入自定义颜色列表
  • markers传入自定义标记样式列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 15:24:03