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

Seaborn swarmplot:修改指定散点的标记形状

修改Seaborn Swarmplot指定类别的标记形状(适配黑白打印)

针对你遇到的AB、AE类别散点标记位置偏移问题,直接提取原swarmplot生成的点坐标再重新绘制是最稳妥的方案,具体步骤如下:

实现代码

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

# 假设你的df、my_palette已经定义完成
df['x_log'] = np.log2(df['value'])  # 匹配log_scale=2后的x轴坐标

# 1. 绘制完整的swarmplot
ax = sns.swarmplot(
    data=df, 
    x="value", 
    y="letter", 
    log_scale=2, 
    hue="type", 
    palette=my_palette, 
    size=6
)

# 2. 提取AB、AE类别的点坐标,并标记需要移除的点
ab_coords = []
ae_coords = []
points_to_remove = []

# 遍历每个散点集合(对应hue的不同type分组)
for collection in ax.collections:
    coords = collection.get_offsets()
    for coord in coords:
        x_log, y_pos = coord
        # 通过y轴位置匹配对应的letter类别
        letter = ax.get_yticklabels()[int(round(y_pos))].get_text()
        if letter == "AB":
            ab_coords.append(coord)
            points_to_remove.append((collection, coord))
        elif letter == "AE":
            ae_coords.append(coord)
            points_to_remove.append((collection, coord))

# 3. 移除原swarmplot中的AB、AE点
for collection, coord in points_to_remove:
    offsets = collection.get_offsets()
    # 过滤掉目标坐标
    new_offsets = offsets[~np.all(offsets == coord, axis=1)]
    collection.set_offsets(new_offsets)

# 4. 重新添加AB、AE类别的点,使用指定标记
# AB用向上三角形标记(5,1),AE用向下三角形标记(5,2)
ax.scatter(
    [c[0] for c in ab_coords], 
    [c[1] for c in ab_coords], 
    marker=(5, 1), 
    s=6**2,  # size对应直径,s是面积,所以取平方
    color="black", 
    zorder=10  # 确保点在最上层
)
ax.scatter(
    [c[0] for c in ae_coords], 
    [c[1] for c in ae_coords], 
    marker=(5, 2), 
    s=6**2, 
    color="black", 
    zorder=10
)

plt.show()

关键说明

  • 直接复用原swarmplot生成的坐标,彻底解决位置偏移问题
  • s参数设置为size²,保证新添加的点和原散点大小一致
  • zorder=10确保自定义标记的点不会被其他散点遮挡
  • 若需要保留原hue的颜色区分,仅修改AB/AE的标记形状,其他点的颜色不受影响,完美适配黑白打印需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 10:52:38