I want to remove some of the buttons from plot toolbar (matplotlib).
I saw that there are some old solutions:
How to modify the navigation too
After trying many solutions, I have found that this works very well.
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)
You can do it by adding following lines of code before creating a plot object:
import matplotlib as mpl
mpl.rcParams['toolbar'] = 'None'
If you want to delete some buttons selectively, you need to redefine the toolitems
variable instead:
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'),
)
I have removed two lines from the original variable mpl.backend_bases.NavigationToolbar2.toolitems
which normally reads:
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'),
)
EDIT
I have realized that it works with backend 'TkAgg'. For the backend 'Qt5Agg' we need to do some additional monkey patching just after modifying toolitems
. Namely:
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