首页 > 解决方案 > 从文本框小部件评估表达式时的 Pyplot 警告

问题描述

如果我有一个带有多个“轴”(正如他们所说的)的 pyplot 图形,并且其中一个中有一个文本框,则在编写一些特殊的字符序列(例如*2)时,我会收到一条警告,指出以下内容:

MatplotlibDeprecationWarning: Toggling axes navigation from the keyboard is deprecated since 3.3 and will be removed two minor releases later.
  return self.func(*args)

请注意,如果我只有一个轴,这似乎不会发生。

我需要使用这样的文本框来插入一个将被评估的函数,所以我需要使用*并且**也许。是什么导致了这个警告?

这是重新创建场景的最小示例:

import matplotlib.pyplot as plt
from matplotlib.widgets import TextBox

fig, (ax1, ax2) = plt.subplots(1, 2)
tb1 = TextBox(ax1, 'Textbox: ')
ax2.plot([1,2,3,4,5])
plt.show()

标签: pythonmatplotlibwarningsaxes

解决方案


看来您可以取消绑定 matplotlib 中的默认键绑定:

import matplotlib.pyplot as plt
from matplotlib.widgets import TextBox

fig, (ax1, ax2) = plt.subplots(1, 2)
fig.canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id)
tb1 = TextBox(ax1, 'Textbox: ')
ax2.plot([1,2,3,4,5])
plt.show()

更多信息在这里- 您显然还可以指定要忽略的绑定。

另一种方法是仅禁止显示此警告:

import warnings
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.widgets import TextBox

with warnings.catch_warnings():
    warnings.simplefilter("ignore", matplotlib.MatplotlibDeprecationWarning)
    fig, (ax1, ax2) = plt.subplots(1, 2)
    tb1 = TextBox(ax1, 'Textbox: ')
    ax2.plot([1,2,3,4,5])
    plt.show()

推荐阅读