在violinplot上叠加swarmplot导致ylim改变、小提琴图被截断
问题:叠加swarmplot后如何调整绘图显示范围
我用seaborn绘制violinplot,叠加swarmplot后出现了显示范围异常的问题,修改figsize无法解决,请问该怎么调整?
复现代码
import seaborn as sns import numpy as np # 生成示例数据 import pandas as pd import matplotlib.pyplot as plt # 原代码遗漏的导入 # 生成示例数据 np.random.seed(365) rows = 60 data1 = {'Type 1': ['a'] * rows, 'Total': np.random.normal(loc=25, scale=3, size=rows)} data2 = {'Type 1': ['b'] * rows, 'Total': np.random.normal(loc=60, scale=7, size=rows)} df = pd.concat([pd.DataFrame(d) for d in [data1, data2]], ignore_index=True) # 绘图 plt.figure(figsize=(5, 4)) sns.violinplot(x='Type 1', y='Total', data=df, inner=None) sns.swarmplot(x='Type 1', y='Total', data=df, color='#000000', size=3) plt.show()
绘图效果
- 叠加swarmplot后的效果:

- 仅violinplot的效果:

示例数据
Type 1 Total 0 a 25.503763 1 a 26.570516 2 a 27.452127 3 a 30.111537 4 a 18.559157 ... 115 b 67.389032 116 b 67.337122 117 b 59.193256 118 b 56.356515 119 b 57.353019
解决方案
方法1:手动设置y轴范围
在绘制完所有图形后,直接指定y轴的上下限,可根据数据极值微调:
# 绘图后添加 plt.ylim(df['Total'].min() - 2, df['Total'].max() + 2)
方法2:保留violinplot的轴范围
先获取violinplot绘制后的轴范围,再绘制swarmplot,最后重置回原范围:
plt.figure(figsize=(5, 4)) ax = plt.gca() # 绘制violinplot并记录轴范围 sns.violinplot(x='Type 1', y='Total', data=df, inner=None, ax=ax) original_ylim = ax.get_ylim() # 绘制swarmplot sns.swarmplot(x='Type 1', y='Total', data=df, color='#000000', size=3, ax=ax) # 重置轴范围 ax.set_ylim(original_ylim) plt.show()
方法3:自动调整布局
调用tight_layout()让matplotlib自动调整图形元素的位置,避免内容被截断:
# 绘图后添加 plt.tight_layout()
内容的提问来源于stack exchange,提问作者Cullen Wise
相关产品推荐
相关产品推荐

