为何无法关闭Matplotlib中的图例警告?
问题原因及解决方案
为什么你的设置没生效?
你遇到的这个UserWarning不属于matplotlib日志系统的管辖范围——它是Python标准库warnings模块发出的,而你用的plt.set_loglevel和logging模块配置只对matplotlib自身的日志输出起作用,管不到这类警告。
两种解决思路
1. 从根源消除警告(推荐)
这个警告的本质是你调用plt.legend()时,当前绘图里没有任何带label属性的元素。只要在绘图时给需要显示图例的元素加上label参数,就能彻底解决:
# 示例:给plot添加label plt.plot(x_data, y_data, label="我的曲线") plt.legend() # 现在不会有警告了
如果你的图根本不需要图例,直接删掉plt.legend()调用就行。
2. 临时屏蔽这个特定警告
如果确实需要保留plt.legend()调用,又不想看到这个警告,可以用warnings模块精准过滤:
import warnings # 只屏蔽这个特定的UserWarning warnings.filterwarnings( "ignore", category=UserWarning, message=r"No artists with labels found to put in legend\." ) # 之后再执行你的绘图代码 logging.getLogger('matplotlib.legend').setLevel(logging.ERROR) plt.set_loglevel("error") plt.legend()
内容的提问来源于stack exchange,提问作者David Banas
相关产品推荐
相关产品推荐

