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

如何基于Pandas DataFrame在一张图中绘制多组散点图

按Tag分组绘制同图X-Y散点图

你提供的DataFrame结构如下:

Tag   X   Y
St2   4   4
st3   7   5
st2   3   2 
st1   2   9
st2   6   4 
st3   2   3 
st1   5   2 

方法一:Matplotlib手动分组绘图(样式可控性强)

import pandas as pd
import matplotlib.pyplot as plt

# 构建示例DataFrame
data = {
    'Tag': ['St2', 'st3', 'st2', 'st1', 'st2', 'st3', 'st1'],
    'X': [4,7,3,2,6,2,5],
    'Y': [4,5,2,9,4,3,2]
}
df = pd.DataFrame(data)
# 统一Tag大小写(避免St2和st2被判定为不同分组,不需要可删除此行)
df['Tag'] = df['Tag'].str.lower()

# 自定义各Tag的颜色和标记样式
tag_styles = {
    'st1': {'color': '#ff4d4d', 'marker': 'o'},
    'st2': {'color': '#3399ff', 'marker': 's'},
    'st3': {'color': '#33cc33', 'marker': '^'}
}

plt.figure(figsize=(8, 6))
# 遍历每个Tag分组绘图
for tag, group_data in df.groupby('Tag'):
    style = tag_styles[tag]
    plt.scatter(
        group_data['X'], group_data['Y'],
        color=style['color'], marker=style['marker'],
        label=tag, s=100
    )

# 添加图表基础元素
plt.xlabel('X')
plt.ylabel('Y')
plt.title('X-Y散点图(按Tag分组)')
plt.legend(title='Tag')
plt.grid(alpha=0.3)
plt.show()

方法二:Seaborn快速实现(代码简洁)

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

# 构建示例DataFrame
data = {
    'Tag': ['St2', 'st3', 'st2', 'st1', 'st2', 'st3', 'st1'],
    'X': [4,7,3,2,6,2,5],
    'Y': [4,5,2,9,4,3,2]
}
df = pd.DataFrame(data)
df['Tag'] = df['Tag'].str.lower()

plt.figure(figsize=(8, 6))
# 通过hue参数自动按Tag分组,style参数区分标记样式
sns.scatterplot(
    data=df, x='X', y='Y',
    hue='Tag', style='Tag',
    s=100
)

plt.xlabel('X')
plt.ylabel('Y')
plt.title('X-Y散点图(按Tag分组)')
plt.grid(alpha=0.3)
plt.show()

说明:如果你的数据中Tag的大小写是刻意区分的,直接删除df['Tag'] = df['Tag'].str.lower()这一行即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:11:15