如何在seaborn的stripplot等分类图中按分类列指定marker样式
seaborn stripplot按分类变量映射marker样式的解决方案
方案1:升级seaborn到0.12.0及以上版本(最简便)
0.12.0之后的seaborn版本中,stripplot、catplot原生支持style参数映射marker样式,直接传入参数即可正常运行:
import seaborn as sns import matplotlib.pyplot as plt tips = sns.load_dataset("tips") # 直接用catplot指定kind为strip sns.catplot( x="day", y="total_bill", hue="time", style="sex", kind="strip", jitter=True, data=tips ) plt.show()
升级seaborn命令:pip install --upgrade seaborn
方案2:基于scatterplot手动添加抖动(兼容性最好)
如果不想升级依赖,可以手动给x轴分类变量添加随机抖动,用原生支持style参数的scatterplot实现完全等效的效果:
import seaborn as sns import numpy as np import matplotlib.pyplot as plt tips = sns.load_dataset("tips") x_col = "day" # 分类转数值编码 x_cats = tips[x_col].unique() x_map = {cat: idx for idx, cat in enumerate(x_cats)} # 生成带抖动的x坐标,抖动幅度和stripplot默认一致 tips["x_jitter"] = tips[x_col].map(x_map) + np.random.uniform(-0.2, 0.2, size=len(tips)) # 绘制散点图,同时映射颜色和marker样式 sns.scatterplot(x="x_jitter", y="total_bill", hue="time", style="sex", data=tips) # 还原x轴刻度为分类名称 plt.xticks(ticks=range(len(x_cats)), labels=x_cats) plt.xlabel(x_col) plt.show()
方案3:低版本seaborn修改stripplot属性
如果必须使用旧版本seaborn,可以先绘制stripplot,再手动修改点的marker样式,补全图例:
import seaborn as sns import matplotlib.pyplot as plt from matplotlib.lines import Line2D tips = sns.load_dataset("tips") ax = sns.stripplot(x="day", y="total_bill", hue="time", jitter=0.2, data=tips) # 定义分类到marker的映射规则 marker_map = {"Male": "o", "Female": "X"} # 遍历所有点修改marker for point, sex in zip(ax.lines, tips["sex"]): point.set_marker(marker_map[sex]) # 构造同时包含hue和style信息的图例 handles = [] for time_val in tips["time"].unique(): for sex_val in tips["sex"].unique(): # 获取对应time的颜色 color = [h.get_color() for h in ax.legend_.legendHandles if h.get_label() == time_val][0] handles.append(Line2D( [], [], marker=marker_map[sex_val], color=color, linestyle="", label=f"{time_val} | {sex_val}" )) ax.legend(handles=handles, title="用餐时间 | 性别") plt.show()
内容的提问来源于stack exchange,提问作者Devil
相关产品推荐
相关产品推荐

