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

Seaborn箱线图:修改图例文本并调整图例矩形尺寸

Fixing Stretched Legend Rectangles After Customizing Labels in Seaborn Boxplots

I’ve run into this exact issue before—when you overwrite legend labels directly with ax.legend(labels=[...]), Matplotlib discards the original Seaborn-generated legend handles and creates new ones from scratch, which default to those annoying stretched rectangles. Here are a few clean ways to fix this:

Method 1: Modify Existing Legend Labels (Simplest)

Instead of creating a new legend, just grab the existing one generated by Seaborn and update its labels. This preserves the original handle dimensions entirely:

import seaborn as sns
import matplotlib.pyplot as plt

# Load sample data and create boxplot
tips = sns.load_dataset("tips")
ax = sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips)

# Get the existing legend and update its labels
legend = ax.get_legend()
legend.set_labels(["Non-smoker", "Smoker"])

plt.show()

Method 2: Reuse Original Handles When Creating a New Legend

If you need to create a new legend for some reason (e.g., reordering items), grab the original handles first and pass them to ax.legend() along with your custom labels:

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")
ax = sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips)

# Get original handles and ignore default labels
handles, _ = ax.get_legend_handles_labels()

# Create new legend with custom labels, reusing original handles
ax.legend(handles=handles, labels=["Non-smoker", "Smoker"])

plt.show()

Method 3: Adjust Handle Dimensions Manually (Last Resort)

If you already used ax.legend(labels=[...]) and want to fix the stretched rectangles after the fact, you can directly modify the width/height of each legend patch:

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")
ax = sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips)

# This creates stretched handles, but we'll fix them
ax.legend(labels=["Non-smoker", "Smoker"])

# Adjust each legend handle's size
for handle in ax.get_legend().get_handles():
    handle.set_width(15)  # Set desired width
    handle.set_height(8)  # Set desired height

plt.show()

The first two methods are preferred because they work with Seaborn’s original legend setup instead of fighting against it.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:30:31