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

如何删除statsmodels中interaction_plot自带的默认图例

问题描述

使用statsmodels库的interaction_plot绘图时,自行添加自定义图例会和函数自动生成的内置图例重复,最终图表显示两个图例。
复现代码:

import numpy as np
np.random.seed(12345)
weight = np.random.randint(1,4,size=60)
duration = np.random.randint(1,3,size=60)
days = np.log(np.random.randint(1,30, size=60))
fig = interaction_plot(weight, duration, days,
             colors=['red','blue'], markers=['D','^'], ms=10)
import matplotlib.pyplot as plt
fig.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), fancybox=True, shadow=True)
plt.show()

运行效果:
重复双图例示例

解决方案

interaction_plot本身没有提供关闭自动图例的参数,它生成的默认图例挂载在函数返回的Axes对象上,只需要在添加自定义图例前,移除这个默认图例即可。
修正后可运行代码:

import numpy as np
import matplotlib.pyplot as plt
from statsmodels.graphics.factorplots import interaction_plot

np.random.seed(12345)
weight = np.random.randint(1,4,size=60)
duration = np.random.randint(1,3,size=60)
days = np.log(np.random.randint(1,30, size=60))
# interaction_plot返回值是Axes对象,命名为ax符合matplotlib惯例
ax = interaction_plot(weight, duration, days,
             colors=['red','blue'], markers=['D','^'], ms=10)
# 删除自动生成的内置图例
ax.get_legend().remove()
# 添加自定义位置和样式的图例
plt.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), fancybox=True, shadow=True)
plt.show()

如果需要使用figure级别的图例(即原代码中调用的fig.legend()写法),只需要把添加图例的代码替换为ax.figure.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), fancybox=True, shadow=True)即可,只要提前移除Axes上的默认图例,就不会出现重复。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 05:03:39