Matplotlib调试:当Python调试打开时,关闭Matplotlib调试以调试程序的其余部分。

3

当我在Python日志记录器中打开DEBUG时,matplotlib会打印出10000行调试代码,而我并不想看到。我尝试过:

plt.set_loglevel("info") 

就像他们的文档中所述,但仍然无法关闭它。我将语句放在导入matplotlib之后,并尝试在使用fig=plt.figure(...)创建图之后立即执行。

都不起作用。有人能帮忙吗? ubuntu20.04,python 3.8.5,matplotlib 3.3.3

2个回答

1
我发现这对于禁用matplotlib日志记录器很有用:
matplotlib.pyplot.set_loglevel (level = 'warning')

如果你将图形保存为png文件,你还需要禁用PIL (PngImagePlugin)记录器。PIL使用logging libary来实现这一点。
要做到这一点:
# get the the logger with the name 'PIL'
pil_logger = logging.getLogger('PIL')  
# override the logger logging level to INFO
pil_logger.setLevel(logging.INFO)

除了使用 INFO 日志级别,您还可以选择其他日志级别:有关日志级别的文档


0
你可以为你的信息创建一个独立的记录器,这样你只记录你需要的内容。
例如,从日志文档Matplotlib示例
import numpy as np
import matplotlib.pyplot as plt
import logging

# create logger
logger = logging.getLogger('no_spam')
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

logger.info("Starting")

x = [1, 2, 3, 4, 5]
y1 = [1, 1, 2, 3, 5]
y2 = [0, 4, 2, 6, 8]
y3 = [1, 3, 5, 7, 9]

y = np.vstack([y1, y2, y3])

labels = ["Fibonacci ", "Evens", "Odds"]

fig, ax = plt.subplots()
ax.stackplot(x, y1, y2, y3, labels=labels)
ax.legend(loc='upper left')
logger.debug("About to show plot")
plt.show()
logger.info("Finished")

这应该生成类似于控制台输出:

2021-01-15 17:33:17,431 - no_spam - INFO - Starting
2021-01-15 17:33:17,635 - no_spam - DEBUG - About to show plot
2021-01-15 17:33:21,491 - no_spam - INFO - Finished

或者,如果您将日志级别设置为INFO

2021-01-15 17:34:18,987 - no_spam - INFO - Starting
2021-01-15 17:34:22,212 - no_spam - INFO - Finished

有趣…让我试试,因为我还不明白为什么Matplotlib的调试信息没有打印出来。非常感谢您抽出时间来帮助我。我会在几分钟内回来的。1号上升! - creeser
当您调用 plt.set_loglevel("info") 时,您正在设置 matplotlib 记录器的日志级别,该记录器正在使用默认记录器。在此示例中,我创建了自己的记录器。如果您正在处理更大的项目,则可以使用单独的记录器进行特定的调试,这样做是有意义的。 - import random
所以,我应该将它设置为Python日志级别: plt.set_loglevel("NOTSET") 来关闭它。谢谢。 - creeser
除非您对matplotlib模块的特定内部感兴趣,否则根本不需要调用plt.set_loglevel(...) - import random

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接