如何在同一画布中绘制两个sns.jointplot图表?
问题描述
希望在同一画布中绘制两个sns.jointplot图表,效果参考对应示例图。目前使用以下代码:
sns.jointplot (draw_D(lst_1)[0], draw_D(lst_1)[1], color = 'r') sns.jointplot (draw_D(lst_2)[0], draw_D(lst_2)[1], color = 'b')
但生成的是两个分开的图表,请问如何解决?
解决方案
sns.jointplot是封装好的高层函数,每次调用都会自动创建新的画布和轴对象,所以直接调用两次会生成独立图表。要在同一画布实现需求,可采用以下两种方法:
方法一:用sns.JointGrid手动构建(推荐)
JointGrid是jointplot的底层类,支持自定义多数据集绘制:
import seaborn as sns import matplotlib.pyplot as plt # 提前获取数据,避免重复调用draw_D x1, y1 = draw_D(lst_1)[0], draw_D(lst_1)[1] x2, y2 = draw_D(lst_2)[0], draw_D(lst_2)[1] # 创建JointGrid基础框架 g = sns.JointGrid() # 在主区域绘制两个数据集的散点图 sns.scatterplot(x=x1, y=y1, color='r', ax=g.ax_joint) sns.scatterplot(x=x2, y=y2, color='b', ax=g.ax_joint) # 绘制顶部边缘直方图 sns.histplot(x=x1, color='r', ax=g.ax_marg_x, kde=False) sns.histplot(x=x2, color='b', ax=g.ax_marg_x, kde=False) # 绘制右侧边缘直方图(设置水平方向) sns.histplot(y=y1, color='r', ax=g.ax_marg_y, kde=False, orientation='horizontal') sns.histplot(y=y2, color='b', ax=g.ax_marg_y, kde=False, orientation='horizontal') # 添加图例区分数据集 g.ax_joint.legend(['数据集1', '数据集2']) plt.show()
方法二:手动搭建matplotlib子布局
如果需要更灵活的布局控制,可直接用matplotlib的网格布局模拟jointplot效果:
import seaborn as sns import matplotlib.pyplot as plt # 提前获取数据 x1, y1 = draw_D(lst_1)[0], draw_D(lst_1)[1] x2, y2 = draw_D(lst_2)[0], draw_D(lst_2)[1] # 创建画布和网格布局,设置宽高比与间距 fig = plt.figure(figsize=(8, 8)) gs = fig.add_gridspec(2, 2, width_ratios=[4,1], height_ratios=[1,4], wspace=0.05, hspace=0.05) # 分配子图轴:主散点图、顶部直方图、右侧直方图 ax_joint = fig.add_subplot(gs[1, 0]) ax_marg_x = fig.add_subplot(gs[0, 0], sharex=ax_joint) ax_marg_y = fig.add_subplot(gs[1, 1], sharey=ax_joint) # 绘制主区域散点图 sns.scatterplot(x=x1, y=y1, color='r', ax=ax_joint) sns.scatterplot(x=x2, y=y2, color='b', ax=ax_joint) # 绘制顶部直方图,隐藏底部刻度标签 sns.histplot(x=x1, color='r', ax=ax_marg_x, kde=False) sns.histplot(x=x2, color='b', ax=ax_marg_x, kde=False) ax_marg_x.tick_params(axis='x', labelbottom=False) # 绘制右侧直方图,隐藏左侧刻度标签 sns.histplot(y=y1, color='r', ax=ax_marg_y, kde=False, orientation='horizontal') sns.histplot(y=y2, color='b', ax=ax_marg_y, kde=False, orientation='horizontal') ax_marg_y.tick_params(axis='y', labelleft=False) # 添加图例 ax_joint.legend(['数据集1', '数据集2']) plt.show()
内容的提问来源于stack exchange,提问作者Houssain Baalbaki
相关产品推荐
相关产品推荐

