如何让Seaborn Jointplot的边际图仅显示图例中的内容?
解决Seaborn jointplot边际图仅显示6种对应颜色轨迹的问题
你的代码中使用hue='rf_number'时,如果rf_number是连续数值,Seaborn会自动生成大量细分类别,导致边际图线条杂乱。要让边际图仅显示图例中的6种颜色对应轨迹,需要先将rf_number转换为6个离散分组,再通过JointGrid手动控制绘制逻辑,具体操作如下:
步骤1:将连续的rf_number分箱为6个离散区间(若已为离散分类可跳过)
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt mask = df['rf_number'].notnull() # 把rf_number切分为6个区间,生成带标签的分类列 df['rf_group'] = pd.cut(df['rf_number'][mask], bins=6, labels=[f'区间{i+1}' for i in range(6)])
步骤2:用JointGrid手动绘制主图和边际图
jointplot是JointGrid的封装,用JointGrid可以完全控制每个分组的边际图绘制:
%matplotlib inline # 初始化JointGrid,指定分组列和调色板 g = sns.JointGrid(data=df[mask], x='x', y='y', hue='rf_group', palette='Spectral', height=12) # 绘制主散点图 g.plot_joint(sns.scatterplot, linewidth=0) # 绘制x轴边际的KDE曲线(每个分组一条) for group_name, group_data in df[mask].groupby('rf_group'): color = g.hue_palette[group_name] sns.kdeplot(group_data['x'], ax=g.ax_marg_x, color=color, label=group_name, linewidth=2) # 绘制y轴边际的KDE曲线(垂直方向) for group_name, group_data in df[mask].groupby('rf_group'): color = g.hue_palette[group_name] sns.kdeplot(group_data['y'], ax=g.ax_marg_y, color=color, label=group_name, vertical=True, linewidth=2) # 设置轴范围 g.ax_joint.set_xlim(-11, 11) g.ax_joint.set_ylim(-10, 10) # 调整图例位置 g.ax_marg_x.legend(title='rf_number范围', bbox_to_anchor=(1.05, 1), loc='upper left') plt.show()
若需要边际图为直方图而非KDE
将上述代码中的sns.kdeplot替换为sns.histplot,并设置histtype='step'以显示空心线条:
# x轴边际直方图 sns.histplot(group_data['x'], ax=g.ax_marg_x, color=color, label=group_name, histtype='step', linewidth=2) # y轴边际直方图 sns.histplot(group_data['y'], ax=g.ax_marg_y, color=color, label=group_name, histtype='step', linewidth=2, orientation='horizontal')
这样处理后,边际图只会显示你指定的6个分组的轨迹,与图例完全对应,不会出现多余线条干扰。
内容的提问来源于stack exchange,提问作者Lucy
相关产品推荐
相关产品推荐

