Seaborn教程:如何添加带新图例的基准点
解决方案:添加BaseLine点到散点图并显示图例
首先修正原数据代码里的拼写错误(peopleBased应为peopleBasedline),然后修改绘图代码,把BaseLine点加入图表并更新图例逻辑,完整代码如下:
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # 数据部分(修正拼写错误) people = [['PeopleA', 157.7, 55.8, 22.4, 'A'], ['PeopleB', 163.9, 100.2, 37.3, 'B'], ['PeopleC', 188.4, 75, 21.1, 'A'], ] peopleBasedline = [['BaseLine', 178, 70]] peopledf = pd.DataFrame(people, columns=['ID', 'Height', 'Weight', 'BMI', 'type']) peoplebaseDf = pd.DataFrame(peopleBasedline, columns=['ID', 'Height', 'Weight']) # 绘图部分 plt.figure(figsize=(12, 9)) sns.set(style="darkgrid") sns.color_palette("mako", as_cmap=True) # 绘制主数据散点图 axes = sns.scatterplot( data=peopledf, x="Height", y="Weight", hue="ID", size="BMI", sizes=(50, 500), legend="auto") # 添加BaseLine点:指定ID作为hue以加入颜色图例,设置固定大小 sns.scatterplot( data=peoplebaseDf, x="Height", y="Weight", hue="ID", s=300, marker='X', legend="auto", ax=axes) # 图例拆分并置于外侧:更新颜色项数量(原3个ID + BaseLine共4个) num_of_colors = len(pd.concat([peopledf, peoplebaseDf])['ID'].unique()) handles, labels = axes.get_legend_handles_labels() color_hl = handles[:num_of_colors], labels[:num_of_colors] sizes_hl = handles[num_of_colors:], labels[num_of_colors:] # 绘制颜色图例 color_leg = axes.legend(*color_hl, bbox_to_anchor=(1.03, 1), loc='upper left', borderaxespad=0.) # 绘制大小图例,微调位置避免重叠 sizes_leg = axes.legend(*sizes_hl, bbox_to_anchor=(1.4, 1), loc='upper left', borderaxespad=0.) axes.add_artist(color_leg) # 调整右侧留白,给图例足够空间 plt.subplots_adjust(right=0.7) plt.show()
关键修改说明:
- 修正数据拼写错误:原代码中创建
peoplebaseDf时误用了peopleBased,改为正确的peopleBasedline,避免报错。 - 添加BaseLine点:单独调用
sns.scatterplot绘制BaseLine,指定hue="ID"让它自动加入颜色图例;用s=300设置固定大小,marker='X'可以让基准点更醒目(可选)。 - 更新图例计数:
num_of_colors改为计算所有唯一ID的数量(包含BaseLine),确保颜色图例能完整包含所有点的标识。 - 微调图例位置:把大小图例的
bbox_to_anchor调整到(1.4, 1),同时缩小plt.subplots_adjust的right值,避免图例超出画布或重叠。
内容的提问来源于stack exchange,提问作者Sun Hao Lun
相关产品推荐
相关产品推荐

