Note
Go to the endto download the full example code.
Tool Manager#
This example demonstrates how to
modify the Toolbar
create tools
add tools
remove tools
usingmatplotlib.backend_managers.ToolManager.
importmatplotlib.pyplotaspltfrommatplotlib.backend_toolsimportToolBase,ToolToggleBaseplt.rcParams['toolbar']='toolmanager'classListTools(ToolBase):"""List all the tools controlled by the `ToolManager`."""default_keymap='m'# keyboard shortcutdescription='List Tools'deftrigger(self,*args,**kwargs):print('_'*80)fmt_tool="{:12}{:45}{}".formatprint(fmt_tool('Name (id)','Tool description','Keymap'))print('-'*80)tools=self.toolmanager.toolsfornameinsorted(tools):ifnottools[name].description:continuekeys=', '.join(sorted(self.toolmanager.get_tool_keymap(name)))print(fmt_tool(name,tools[name].description,keys))print('_'*80)fmt_active_toggle="{!s:12}{!s:45}".formatprint("Active Toggle tools")print(fmt_active_toggle("Group","Active"))print('-'*80)forgroup,activeinself.toolmanager.active_toggle.items():print(fmt_active_toggle(group,active))classGroupHideTool(ToolToggleBase):"""Show lines with a given gid."""default_keymap='S'description='Show by gid'default_toggled=Truedef__init__(self,*args,gid,**kwargs):self.gid=gidsuper().__init__(*args,**kwargs)defenable(self,*args):self.set_lines_visibility(True)defdisable(self,*args):self.set_lines_visibility(False)defset_lines_visibility(self,state):foraxinself.figure.get_axes():forlineinax.get_lines():ifline.get_gid()==self.gid:line.set_visible(state)self.figure.canvas.draw()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 createdfig.canvas.manager.toolmanager.add_tool('List',ListTools)fig.canvas.manager.toolmanager.add_tool('Show',GroupHideTool,gid='mygroup')# Add an existing tool to new group `foo`.# It can be added as many times as we wantfig.canvas.manager.toolbar.add_tool('zoom','foo')# Remove the forward buttonfig.canvas.manager.toolmanager.remove_tool('forward')# To add a custom tool to the toolbar at specific location inside# the navigation groupfig.canvas.manager.toolbar.add_tool('Show','navigation',1)plt.show()