如何从Matplotlib中删除工具栏按钮

时间:2019-04-21 04:41:58

标签: python matplotlib

我想从绘图工具栏(matplotlib)中删除一些按钮。

我看到有一些旧的解决方案:

  

How to modify the navigation toolbar easily in a matplotlib figure window?

但是所有答案都使用GUI框架(QT,TKinter)。

是否有不使用GUI框架的新解决方案?

enter image description here

2 个答案:

答案 0 :(得分:3)

您可以通过在创建打印对象之前添加以下代码行来实现:

import matplotlib as mpl
mpl.rcParams['toolbar'] = 'None' 

如果要有选择地删除一些按钮,则需要重新定义toolitems变量:

from matplotlib import backend_bases
# mpl.rcParams['toolbar'] = 'None'
backend_bases.NavigationToolbar2.toolitems = (
        ('Home', 'Reset original view', 'home', 'home'),
        ('Back', 'Back to  previous view', 'back', 'back'),
        ('Forward', 'Forward to next view', 'forward', 'forward'),
        (None, None, None, None),
        ('Zoom', 'Zoom to rectangle', 'zoom_to_rect', 'zoom'),
        (None, None, None, None),
        ('Save', 'Save the figure', 'filesave', 'save_figure'),
      )

我从通常读取为以下内容的原始变量mpl.backend_bases.NavigationToolbar2.toolitems中删除了两行:

toolitems = (
    ('Home', 'Reset original view', 'home', 'home'),
    ('Back', 'Back to  previous view', 'back', 'back'),
    ('Forward', 'Forward to next view', 'forward', 'forward'),
    (None, None, None, None),
    ('Pan', 'Pan axes with left mouse, zoom with right', 'move', 'pan'),
    ('Zoom', 'Zoom to rectangle', 'zoom_to_rect', 'zoom'),
    ('Subplots', 'Configure subplots', 'subplots', 'configure_subplots'),
    (None, None, None, None),
    ('Save', 'Save the figure', 'filesave', 'save_figure'),
  )

编辑

我已经意识到它可以与后端“ TkAgg”一起使用。对于后端“ Qt5Agg”,我们需要在修改toolitems之后立即进行一些其他的猴子修补。即:

if matplotlib.get_backend() == 'Qt5Agg':
    from matplotlib.backends.backend_qt5 import NavigationToolbar2QT
    def _update_buttons_checked(self):
        # sync button checkstates to match active mode (patched)
        if 'pan' in self._actions:
            self._actions['pan'].setChecked(self._active == 'PAN')
        if 'zoom' in self._actions:
            self._actions['zoom'].setChecked(self._active == 'ZOOM')
    NavigationToolbar2QT._update_buttons_checked = _update_buttons_checked

答案 1 :(得分:0)

尝试了许多解决方案后,我发现这非常有效。

toolbar = plt.get_current_fig_manager().toolbar
unwanted_buttons = ['Subplots','Save']
for x in toolbar.actions():
    if x.text() in unwanted_buttons:
        toolbar.removeAction(x)