为什么我不能在Matplotlib中关闭图例警告?

编程语言 2026-07-09

有人知道为什么这不工作吗?

plot.py:

355    logging.getLogger('matplotlib.legend').setLevel(logging.ERROR)
356    plt.set_loglevel("error")
357    plt.legend()

我得到的是这个:

plot.py:357: UserWarning: No artists with labels found to put in legend.
Note that artists whose label start with an underscore are ignored when
legend() is called with no argument.
  plt.legend()

解决方案

特别感谢 furas 提供的线索,促成了这个答案:

with warnings.catch_warnings():
    warnings.simplefilter("ignore", category=UserWarning)
    {many `plt.<function>` lines omitted.}
    plt.legend()

现在,在我的输出中,那个 plt.legend() 行不会再弹出恼人的警告了,这正是我想要达到的效果。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章