You are reading an old version of the documentation (v1.5.1). For the latest version see

We're updating the default styles for Matplotlib 2.0

Learn what to expect in the new updates



This Page

user_interfaces example code: toolmanager.pyΒΆ

[source code]

'''This example demonstrates how to:
* Modify the Toolbar
* Create tools
* Add tools
* Remove tools
Using `matplotlib.backend_managers.ToolManager`

from __future__ import print_function
import matplotlib
matplotlib.rcParams['toolbar'] = 'toolmanager'
import matplotlib.pyplot as plt
from matplotlib.backend_tools import ToolBase, ToolToggleBase
from gi.repository import Gtk, Gdk

class ListTools(ToolBase):
    '''List all the tools controlled by the `ToolManager`'''
    # keyboard shortcut
    default_keymap = 'm'
    description = 'List Tools'

    def trigger(self, *args, **kwargs):
        print('_' * 80)
        print("{0:12} {1:45} {2}".format('Name (id)',
                                         'Tool description',
        print('-' * 80)
        tools =
        for name in sorted(tools.keys()):
            if not tools[name].description:
            keys = ', '.join(sorted(self.toolmanager.get_tool_keymap(name)))
            print("{0:12} {1:45} {2}".format(name,
        print('_' * 80)
        print("Active Toggle tools")
        print("{0:12} {1:45}".format("Group", "Active"))
        print('-' * 80)
        for group, active in self.toolmanager.active_toggle.items():
            print("{0:12} {1:45}".format(group, active))

class GroupHideTool(ToolToggleBase):
    '''Hide lines with a given gid'''
    default_keymap = 'G'
    description = 'Hide by gid'

    def __init__(self, *args, **kwargs):
        self.gid = kwargs.pop('gid')
        ToolToggleBase.__init__(self, *args, **kwargs)

    def enable(self, *args):

    def disable(self, *args):

    def set_lines_visibility(self, state):
        gr_lines = []
        for ax in self.figure.get_axes():
            for line in ax.get_lines():
                if line.get_gid() == self.gid:

fig = plt.figure()
plt.plot([1, 2, 3], gid='mygroup')
plt.plot([2, 3, 4], gid='unknown')
plt.plot([3, 2, 1], gid='mygroup')

# Add the custom tools that we created
fig.canvas.manager.toolmanager.add_tool('List', ListTools)
fig.canvas.manager.toolmanager.add_tool('Hide', GroupHideTool, gid='mygroup')

# Add an existing tool to new group `foo`.
# It can be added as many times as we want
fig.canvas.manager.toolbar.add_tool('zoom', 'foo')

# Remove the forward button

# To add a custom tool to the toolbar at specific location inside
# the navigation group
fig.canvas.manager.toolbar.add_tool('Hide', 'navigation', 1)

Keywords: python, matplotlib, pylab, example, codex (see Search examples)