Friday, 8 January 2021

Suppress Matplotlib Legend Warning in IPython

I am creating a plot with a large amount of data and adding a legend to it:

import matplotlib.pyplot as plt
import numpy as np

plt.plot(np.arange(100000), np.random.random((100000, 10)), label='data')
plt.legend()

This generates a warning (as expected), when the legend actually gets drawn in another thread:

<matplotlib.legend.Legend at 0x1b5824d04c8>C:\Users\...\lib\site-packages\ipykernel\eventloops.py:106: UserWarning: Creating legend with loc="best" can be slow with large amounts of data.
  app.exec_()

I would like to suppress this specific warning, so I do

from warnings import filterwarnings
filterwarnings("ignore", category=UserWarning, module="matplotlib")

Running the same plotting code again produces the same warning.

How do I suppress it? Ideally, I would like to use warnings.catch_warnings around the call to legend. Something like

with warnings.catch_warnings():
    plt.legend()

The original commands were run in interactive mode in spyder (ipython) using a Qt5agg backend. I also ran the same commands followed by plt.show() in a plain python console:

__main__:1: UserWarning: Creating legend with loc="best" can be slow with large amounts of data.

Running filterwarnings("ignore", category=UserWarning, module="__main__") helps, but only in non-interactive mode. In interactive mode, the following warning is issued:

C:\Users\...\lib\site-packages\pyreadline\console\console.py:514: UserWarning: Creating legend with loc="best" can be slow with large amounts of data.
  call_function(inputHookFunc, ())

The issue seems to be ipython specific. I am using

Python 3.8.3, IPython 7.16.1, matplotlib 3.2.2 (, and numpy 1.18.5)



from Suppress Matplotlib Legend Warning in IPython

No comments:

Post a Comment