如何在Seaborn中于X轴下方堆叠rugplots?
在Seaborn中实现X轴下方的堆叠Rugplot效果
当然可以实现!Seaborn的rugplot虽然没有直接提供堆叠参数,但通过手动调整每个rugplot的垂直位置和显示高度,就能轻松把它们堆叠在X轴下方。
实现步骤与代码示例
下面是完整的实现代码,包含数据生成、堆叠rugplot绘制,还可以搭配分布曲线(类似你提到的示例图效果):
import seaborn as sns import numpy as np import matplotlib.pyplot as plt # 生成3组示例数据集 np.random.seed(42) data_set1 = np.random.normal(0, 1, 100) data_set2 = np.random.normal(2, 1.2, 100) data_set3 = np.random.normal(-1, 0.8, 100) # 创建画布和坐标轴 fig, ax = plt.subplots(figsize=(8, 5)) # 在X轴上方绘制对应的核密度曲线(可选,对应示例图的分布曲线) sns.kdeplot(data_set1, ax=ax, color='#1f77b4', linewidth=1.5) sns.kdeplot(data_set2, ax=ax, color='#ff7f0e', linewidth=1.5) sns.kdeplot(data_set3, ax=ax, color='#2ca02c', linewidth=1.5) # 在X轴下方堆叠绘制rugplot # 通过`y`参数设置垂直位置(负数表示X轴下方),`height`控制rug的长度 sns.rugplot(data_set1, ax=ax, height=0.05, y=-0.1, color='#1f77b4', label='数据集1') sns.rugplot(data_set2, ax=ax, height=0.05, y=-0.2, color='#ff7f0e', label='数据集2') sns.rugplot(data_set3, ax=ax, height=0.05, y=-0.3, color='#2ca02c', label='数据集3') # 调整坐标轴显示 ax.set_ylim(-0.4, 1.2) # 扩大y轴范围,确保所有rugplot都显示 ax.set_yticks([]) # 隐藏y轴刻度 ax.set_yticklabels([]) # 隐藏y轴标签 # 添加图例和标题 ax.legend(loc='upper right') ax.set_title('带分布曲线的X轴下方堆叠Rugplot') plt.tight_layout() plt.show()
关键参数说明
y:设置每个rugplot的垂直位置,使用负数就能把rug放在X轴下方,不同的数值对应不同的堆叠层级(比如-0.1、-0.2、-0.3依次向下排列)。height:控制每个rug刻度的长度,数值越小,rug越短,避免堆叠时互相遮挡。- 搭配
kdeplot:如果需要像示例图那样展示分布曲线,直接在同一个坐标轴上绘制即可,视觉上更完整。
内容的提问来源于stack exchange,提问作者NNN
相关产品推荐
相关产品推荐

