You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在seaborn boxenplot中绘制多列并实现两张图表并排展示

Seaborn boxenplot并排布局实现方案

你可以通过matplotlib的子图网格功能实现两个图表并排展示,修改后的完整代码如下:

import pandas as pd 
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme(style="whitegrid")

# 生成1行2列的子图容器,figsize可自行调整画布大小
fig, (ax_left, ax_right) = plt.subplots(nrows=1, ncols=2, figsize=(12, 5))

# 左子图画members分布
sns.boxenplot(x=expeditions["nbre_members"], color="r", ax=ax_left)
ax_left.set_xlabel("Nombre de membres")
ax_left.set_title("Membres 数量分布")

# 右子图画hired_staff分布
sns.boxenplot(x=expeditions["hired_staff"], color="b", ax=ax_right)
ax_right.set_xlabel("Nombre de hired_staff")
ax_right.set_title("Hired_staff 数量分布")

# 全局标题设置,y参数可调整标题和图表的间距
fig.suptitle("Répartition du nombre de membres/hired_staff", y=1.03)
# 修正原代码错误的legend传参
plt.legend(["members", "hired_staff"])
# 自动调整子图间距避免元素重叠
plt.tight_layout()
plt.show()

核心改动逻辑:

  • 调用plt.subplots(1,2)创建一行两列的子图网格,返回的两个ax对象分别对应左右两个子图的绘图坐标
  • 绘制每个boxenplot时新增ax参数,指定绘图的子图位置,避免两张图堆叠到同一个画布上
  • 子图的坐标轴标签、标题需要通过对应ax对象的set_*方法设置,不要使用plt的全局方法,避免配置不生效
  • 额外补充plt.tight_layout()自动适配子图间距,解决标签、标题重叠的问题

如果需要两张图共用x/y轴方便数值对比,可以在plt.subplots中新增sharex=True/sharey=True参数即可。

内容的提问来源于stack exchange,提问作者easy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 22:36:04