matplotlib DEBUG Turn off when python DEBUG is on to debug rest of program

Viewed 1126

When I turn on DEBUG in the python logger, matplotlib prints 10,000 lines of debug code that I do not want to see. I tried:

plt.set_loglevel("info") 

as in their documentation, but still doesn't turn it off. I put the statement right after importing matplotlib, and tried it right after creating the plot with fig=plt.figure(...).

Neither works. Help? ubuntu20.04, python 3.8.5, matplotlib 3.3.3

1 Answers

You can create a separate logger for your messages so you log only what you require.

E.g. from logging doc and Matplotlib example.

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")

This should generate console output like:

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

Or, if you set the logging level to INFO:

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