使用Seaborn kdeplot()并排绘图时边缘分布缺失问题
问题解决:合并子图后边缘分布不显示的修复
问题原因
你当前使用sns.kdeplot(kind="kde")仅绘制了二维联合密度图,未生成边缘分布;而seaborn.jointplot是独立的Figure对象,无法直接嵌入到plt.subplots创建的子图中。要实现带边缘分布的二维图并嵌入子图,需用seaborn.JointGrid手动构建。
修正后的完整代码
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import ot import ot.plot # 定义双变量正态分布的均值和协方差 mean1 = [0, 0] cov1 = [[1, 0.5], [0.5, 1]] mean2 = [3, 3] cov2 = [[1, -0.5], [-0.5, 1]] n = 100 # 生成样本 np.random.seed(0) samples1 = np.random.multivariate_normal(mean1, cov1, size=n) samples2 = np.random.multivariate_normal(mean2, cov2, size=n) df1 = pd.DataFrame(np.concatenate([samples1, samples2]), columns=['X', 'Y']) df1['Distribution'] = 'Target' df1['Distribution'].iloc[n:] = 'Source' # 自定义配色 custom_palette = {'Target': 'blue', 'Source': 'red'} # 创建并排子图 fig, axs = plt.subplots(1, 2, figsize=(14, 5)) # 左侧:带边缘分布的二维密度图 # 使用JointGrid绑定到指定子图 g = sns.JointGrid(data=df1, x="X", y="Y", hue="Distribution", palette=custom_palette, space=0, ax_joint=axs[0]) # 绘制联合密度图 g.plot_joint(sns.kdeplot, fill=True, alpha=0.6) # 绘制X轴边缘分布 g.plot_marginals(sns.kdeplot, fill=True, alpha=0.6) # 设置坐标轴范围 g.ax_joint.set_xlim(-4, 6.5) g.ax_joint.set_ylim(-4, 6.5) # 移动图例位置 sns.move_legend(g.ax_joint, "lower right") # 右侧:最优传输匹配图 a, b = np.ones((n,)) / n, np.ones((n,)) / n # 样本上的均匀分布 M = ot.dist(samples2, samples1, metric='euclidean') G0 = ot.emd(a, b, M) # 绘制匹配连线,指定axes为axs[1] ot.plot.plot2D_samples_mat(samples2, samples1, G0, c=[.5, .5, 1], ax=axs[1]) axs[1].plot(samples2[:, 0], samples2[:, 1], '+r', markersize=10, label='Source samples') axs[1].plot(samples1[:, 0], samples1[:, 1], 'xb', markersize=10, label='Target samples') axs[1].legend(loc=4) # 统一坐标轴设置 for ax in axs: ax.set(xlabel='X') ax.set_xlim([-4, 6.5]) ax.set_ylim([-4, 6.5]) # 隐藏右侧子图的Y轴 axs[1].set(ylabel='') axs[1].yaxis.set_visible(False) # 调整布局 fig.tight_layout() plt.show()
关键修改点
- 用
seaborn.JointGrid替代sns.kdeplot,通过ax_joint参数将其绑定到plt.subplots创建的子图上 - 分别调用
plot_joint和plot_marginals绘制联合密度图和边缘分布 - 绘制最优传输连线时,通过
ax参数指定使用右侧子图,避免默认创建新图 - 调整了整体图尺寸,避免边缘分布被挤压
内容的提问来源于stack exchange,提问作者Lyft
相关产品推荐
相关产品推荐

