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

设置坐标轴外图例时sns.histplot图例无法完整显示

解决图例保存时被截断的问题

你遇到的问题是因为matplotlib默认保存的画布范围仅包含坐标轴区域,没有将轴外的图例纳入其中。以下几种方法可以解决这个问题:

方法1:保存时使用bbox_inches='tight'参数

直接在plt.savefig中添加该参数,它会自动扩展保存边界,包含所有可见元素:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df_long = pd.DataFrame({
    "Category": ["A", "B", "C", "D", "A", "B", "C", "D", "A", "B", "C", "D", "A", "B", "C", "D"],
    "Round": ["Round1", "Round1", "Round1", "Round1", "Round2", "Round2", "Round2", "Round2", "Round3", "Round3", "Round3", "Round3", "Round4", "Round4", "Round4", "Round4"],
    "Value": [10, 20, 10, 30, 20, 25, 15, 25, 12, 15, 19, 6, 10, 29, 13, 19]
})
ax = sns.histplot(df_long, x="Category", hue="Round", weights="Value",
                  multiple="stack",
                  shrink=.8,
                  )
ax.set_ylabel('Weight')
legend = ax.get_legend()
legend.set_bbox_to_anchor((1, 1))

# 保存时添加bbox_inches参数
plt.savefig("histogram.png", bbox_inches='tight')
plt.savefig("histogram.pdf", bbox_inches='tight')

方法2:手动调整子图布局

通过plt.subplots_adjust给右侧预留足够空间放置图例,避免被截断:

# 前面绘图代码保持不变

# 调整右侧边距,为图例留出空间
plt.subplots_adjust(right=0.8)
plt.savefig("histogram.png")
plt.savefig("histogram.pdf")

方法3:创建画布时启用tight_layout

在初始化画布时设置tight_layout=True,让matplotlib自动调整布局:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# 创建画布时启用tight_layout
fig, ax = plt.subplots(tight_layout=True)
df_long = pd.DataFrame({
    "Category": ["A", "B", "C", "D", "A", "B", "C", "D", "A", "B", "C", "D", "A", "B", "C", "D"],
    "Round": ["Round1", "Round1", "Round1", "Round1", "Round2", "Round2", "Round2", "Round2", "Round3", "Round3", "Round3", "Round3", "Round4", "Round4", "Round4", "Round4"],
    "Value": [10, 20, 10, 30, 20, 25, 15, 25, 12, 15, 19, 6, 10, 29, 13, 19]
})
sns.histplot(df_long, x="Category", hue="Round", weights="Value",
             multiple="stack",
             shrink=.8,
             ax=ax
             )
ax.set_ylabel('Weight')
legend = ax.get_legend()
legend.set_bbox_to_anchor((1, 1))

plt.savefig("histogram.png")
plt.savefig("histogram.pdf")

其中方法1操作最简单,推荐优先使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 02:49:58