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

如何根据DataFrame字段值设置Seaborn swarmplot标记的边缘颜色

实现方法

你可以在绘制完swarmplot后,手动获取散点集合对象,为每个点单独设置边缘色,完整实现代码如下:

import seaborn as sns
import matplotlib.pyplot as plt

# 构建车手填充色映射字典
driver_color_map = df.drop_duplicates("Driver").set_index("Driver")["Colour"].to_dict()

# 绘制箱线图
ax = sns.boxplot(x="Driver", y="LapTimeSeconds", data=df, width=0.8, color="white")

# 绘制蜂群图,指定填充色对应车手专属色
swarm_plot = sns.swarmplot(
    x="Driver",
    y="LapTimeSeconds",
    data=df,
    size=9,
    linewidth=1,
    palette=driver_color_map,
    hue="Driver",
    legend=False
)

# 为每个散点设置对应Compound的边缘色
swarm_plot.collections[0].set_edgecolor(df["Compound_colour"].tolist())

plt.show()

原理解释

  • 首先通过字典映射保证每个车手的散点填充色和Colour列完全匹配,新增hue="Driver"是为了适配Seaborn 0.12及以上版本的palette参数规则,避免告警。
  • swarm_plot.collections[0]对应swarmplot生成的所有散点集合,Seaborn绘制散点的顺序和DataFrame的行顺序完全一致,因此直接传入Compound_colour列的取值列表,就可以为每个点匹配到对应的边缘色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:54:04