[英]Suppress WARNING:matplotlib.legend:No handles with labels found to put in legend
[英]Suppress Matplotlib Legend Warning in IPython
我正在創建一個包含大量數據的 plot 並向其添加圖例:
import matplotlib.pyplot as plt
import numpy as np
plt.plot(np.arange(100000), np.random.random((100000, 10)), label='data')
plt.legend()
當圖例實際在另一個線程中繪制時,這會生成警告(如預期的那樣):
<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_()
我想抑制這個特定的警告,所以我這樣做
from warnings import filterwarnings
filterwarnings("ignore", category=UserWarning, module="matplotlib")
再次運行相同的繪圖代碼會產生相同的警告。
我該如何抑制它? 理想情況下,我想在對legend
的調用周圍使用warnings.catch_warnings
。 就像是
with warnings.catch_warnings():
plt.legend()
原始命令使用Qt5agg
后端在 spyder (ipython) 中以交互模式運行。 我還在一個普通的 python 控制台中運行了相同的命令,然后是plt.show()
:
__main__:1: UserWarning: Creating legend with loc="best" can be slow with large amounts of data.
運行filterwarnings("ignore", category=UserWarning, module="__main__")
幫助,但僅限於非交互模式。 在交互模式下,發出以下警告:
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, ())
這個問題似乎是特定於 ipython 的。 我在用
Python 3.8.3、IPython 7.16.1、matplotlib 3.2.2(和 numpy 1.18.5)
此答案顯示了如何根據 OP 標題抑制圖例警告。 它沒有解釋如何在發出警告后暫時捕獲警告。 如果您對后者感興趣,那么以下內容更像是一種解決方法而不是答案。
根據源代碼,如果使用默認位置(來自默認為'best'
的rcParams['legend.loc']
,則會顯示警告,並且需要超過 1 秒才能找到最佳位置。 如果您明確將位置設置為'best'
則不會發出警告。
在 Windows 上測試,IPython 和普通命令行(我不得不增加我機器上的數字):
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1)
plt.plot(np.arange(1_000_000), np.random.random((1_000_000, 10)), label='data')
plt.legend(loc='best')
plt.show()
作為替代方案,您可以通過其消息(而不是module )永久抑制警告:
filterwarnings("ignore", 'Creating legend with loc="best" can be slow with large amounts of data.')
缺點是它是永久性的。 我找不到通過使用上下文管理暫時抑制警告的方法,因為上下文當然在圖例 position 計算發生之前很久就關閉了。
要將此更改恢復到警告過濾器列表,您可以在最終繪制圖例后執行以下操作之一: warnings.filters = [w for w in warnings.filters if not w[1] or not re.match(w[1], 'Creating legend with loc="best" can be slow with large amounts of data.')]
或filterwarnings("default", 'Creating legend with loc="best" can be slow with large amounts of data.')
.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.