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

matplotlib_venn右上角图例被截断,如何移动图例?

解决韦恩图图例被截断的方法

当然可以通过调整图例位置或画布布局解决截断问题,以下是几个实用方案:

方法1:手动指定图例位置

venn3_unweighted会返回韦恩图对象,通过它获取图例标签后,用bbox_to_anchor参数自定义图例位置,比如放到图的右侧外部:

from matplotlib import pyplot as plt
from matplotlib_venn import venn3_unweighted

plt.style.use('seaborn')

plt.figure(figsize=(5, 5))
# 获取韦恩图实例
vd = venn3_unweighted(
    subsets=(703, 659, 5205, 3444, 1583, 1580, 17280),
    set_labels=('Nlab (45,309 genes)', 'Nqld (49,639 genes)', 'Ngla (53,626 genes)')
)
# 把图例移到右侧偏上的位置,(1.2, 1)是相对坐标
plt.legend(handles=vd.set_labels, bbox_to_anchor=(1.2, 1))

plt.show()

方法2:增大图像尺寸

直接扩大画布尺寸,给图例留出足够显示空间:

from matplotlib import pyplot as plt
from matplotlib_venn import venn3_unweighted

plt.style.use('seaborn')

# 把figsize从(5,5)调大到(8,8)
plt.figure(figsize=(8, 8))
venn3_unweighted(
    subsets=(703, 659, 5205, 3444, 1583, 1580, 17280),
    set_labels=('Nlab (45,309 genes)', 'Nqld (49,639 genes)', 'Ngla (53,626 genes)')
)

plt.show()

方法3:调整子图边距

通过subplots_adjust增大右侧边距,让图例能完整显示在画布内:

from matplotlib import pyplot as plt
from matplotlib_venn import venn3_unweighted

plt.style.use('seaborn')

plt.figure(figsize=(5, 5))
venn3_unweighted(
    subsets=(703, 659, 5205, 3444, 1583, 1580, 17280),
    set_labels=('Nlab (45,309 genes)', 'Nqld (49,639 genes)', 'Ngla (53,626 genes)')
)
# 调整右侧边距为0.8,默认值更小,会挤压图例空间
plt.subplots_adjust(right=0.8)

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:50:39