python matplotlib工具欄源碼探析三之添加、刪除自定義工具項(xiàng)的案例詳解
matplotlib工具欄源碼探析二(添加、刪除內(nèi)置工具項(xiàng))探討了工具欄內(nèi)置工具項(xiàng)的管理,除了內(nèi)置工具項(xiàng),很多場景中需要自定義工具項(xiàng),官方給出了案例https://matplotlib.org/gallery/user_interfaces/toolmanager_sgskip.html,主要基于matplotlib.backend_managers.ToolManager類實(shí)現(xiàn),即使用工具欄管理器模式。
官方案例解析
下面對(duì)官方案例關(guān)鍵點(diǎn)做注釋說明。
import matplotlib.pyplot as plt
# 設(shè)置工具欄使用工具欄管理器模式
plt.rcParams['toolbar'] = 'toolmanager'
# 導(dǎo)入工具項(xiàng)的基類ToolBase和ToolToggleBase
from matplotlib.backend_tools import ToolBase, ToolToggleBase
# 因?yàn)楣ぞ唔?xiàng)必須以類的形式添加,所以創(chuàng)建自定義基本工具項(xiàng)類,基類為ToolBase
class ListTools(ToolBase):
# 該工具項(xiàng)的功能為列出工具欄管理器管理的所有工具項(xiàng)
"""List all the tools controlled by the `ToolManager`."""
# 設(shè)置默認(rèn)快捷鍵和工具項(xiàng)描述
default_keymap = 'm'
description = 'List Tools'
# 定義工具項(xiàng)被觸發(fā)時(shí)的動(dòng)作
def trigger(self, *args, **kwargs):
print('_' * 80)
print("{0:12} {1:45} {2}".format(
'Name (id)', 'Tool description', 'Keymap'))
print('-' * 80)
# 獲取工具欄管理器管理的所有工具項(xiàng)
tools = self.toolmanager.tools
# 輸出各個(gè)工具項(xiàng)
for name in sorted(tools):
if not tools[name].description:
continue
keys = ', '.join(sorted(self.toolmanager.get_tool_keymap(name)))
print("{0:12} {1:45} {2}".format(
name, tools[name].description, keys))
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(str(group), str(active)))
# 基于ToolToggleBase創(chuàng)建自定義切換式工具項(xiàng),切換式工具項(xiàng)在觸發(fā)時(shí)會(huì)在生效和失效兩種狀態(tài)之間切換
class GroupHideTool(ToolToggleBase):
# 該工具項(xiàng)的功能為根據(jù)分組切換顯示/隱藏?cái)?shù)據(jù)元素
"""Show lines with a given gid."""
# 設(shè)置默認(rèn)快捷鍵和工具項(xiàng)描述
default_keymap = 'G'
description = 'Show by gid'
default_toggled = True
# 構(gòu)造函數(shù)的參數(shù)gid為數(shù)據(jù)元素的分組
def __init__(self, *args, gid, **kwargs):
self.gid = gid
super().__init__(*args, **kwargs)
# 定義工具項(xiàng)生效時(shí)的方法
def enable(self, *args):
self.set_lines_visibility(True)
# 定義工具項(xiàng)失效時(shí)的方法
def disable(self, *args):
self.set_lines_visibility(False)
def set_lines_visibility(self, state):
for ax in self.figure.get_axes():
for line in ax.get_lines():
if line.get_gid() == self.gid:
line.set_visible(state)
# 注意!在圖像生成之后,修改圖像中的元素必須重繪
self.figure.canvas.draw()
fig = plt.figure()
# 注意通過gid屬性可以為數(shù)據(jù)元素分組
plt.plot([1, 2, 3], gid='mygroup')
plt.plot([2, 3, 4], gid='unknown')
plt.plot([3, 2, 1], gid='mygroup')
# 將自定義的工具項(xiàng)添加添加到工具欄管理器,格式為 工具項(xiàng)名稱 工具項(xiàng)類 其他參數(shù)
fig.canvas.manager.toolmanager.add_tool('List', ListTools)
fig.canvas.manager.toolmanager.add_tool('Show', GroupHideTool, gid='mygroup')
# 可以反復(fù)添加已存在的工具項(xiàng)
# 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')
# 刪除工具項(xiàng)
# Remove the forward button
fig.canvas.manager.toolmanager.remove_tool('forward')
# 新添加到工具欄管理器的工具項(xiàng)還不能直接使用,需要通過toolbar對(duì)象添加到當(dāng)前工具欄
# 如果不將自定義的工具項(xiàng)添加到工具欄管理器,直接使用toolbar對(duì)象添加則會(huì)報(bào)錯(cuò)
# 將自定義的工具項(xiàng)Show添加到內(nèi)置的navigation組的特定位置(即組內(nèi)第2個(gè)位置)
# To add a custom tool to the toolbar at specific location inside
# the navigation group
fig.canvas.manager.toolbar.add_tool('Show', 'navigation', 1)
#fig.canvas.manager.toolbar.add_tool('List', 'navigation', 2)
plt.show()
官方案例運(yùn)行結(jié)果
運(yùn)行后自定義的Show按鈕處于生效狀態(tài),3條線全部顯示。

點(diǎn)擊Show按鈕,使之處理失效狀態(tài),mygroup組的兩條線不再顯示。

由于案例中僅將List工具項(xiàng)添加到工具欄管理器,但是沒有添加到工具欄中,因此List工具項(xiàng)未在工具欄中顯示。但是List工具項(xiàng)的快捷鍵m是生效的,在界面上按快捷鍵m,控制臺(tái)輸出以下信息。
________________________________________________________________________________
Name (id) Tool description Keymap
--------------------------------------------------------------------------------
List List Tools m
Show Show by gid G
allnav Enable all axes toolmanager a
back Back to previous view MouseButton.BACK, backspace, c, left
copy Copy the canvas figure to clipboard cmd+c, ctrl+c
fullscreen Toggle fullscreen mode ctrl+f, f
grid Toggle major grids g
grid_minor Toggle major and minor grids
help Print tool list, shortcuts and description f1
home Reset original view h, home, r
nav Enable one axes toolmanager 1, 2, 3, 4, 5, 6, 7, 8, 9
pan Pan axes with left mouse, zoom with right p
quit Quit the figure cmd+w, ctrl+w, q
quit_all Quit all figures
save Save the figure ctrl+s, s
subplots Configure subplots
xscale Toggle scale X axis L, k
yscale Toggle scale Y axis l
zoom Zoom to rectangle o
________________________________________________________________________________
Active Toggle tools
Group Active
--------------------------------------------------------------------------------
default None
None {'Show'}
總結(jié)
matplotlib支持兩種工具項(xiàng):基本工具項(xiàng)(基類ToolBase)和切換式工具項(xiàng)(基類ToolToggleBase)。
基本工具項(xiàng)需要注意定義trigger方法,即工具項(xiàng)被觸發(fā)時(shí)的動(dòng)作。
切換式工具項(xiàng)需要注意定義enable和disable方法,即生效和失效兩種狀態(tài)的動(dòng)作,如方法定義中牽扯到修改圖像,需要注意重繪圖像。
注意添加自定義工具項(xiàng)的流程!先將自定義的工具項(xiàng)添加到工具欄管理器,然后再添加到當(dāng)前工具欄!內(nèi)置工具項(xiàng)之所以不用添加到工具欄管理器是因?yàn)樗鼈儽旧砭鸵呀?jīng)添加在工具欄管理器!
到此這篇關(guān)于matplotlib工具欄源碼探析三之添加、刪除自定義工具項(xiàng)的文章就介紹到這了,更多相關(guān)matplotlib工具欄內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- python判斷圖片寬度和高度后刪除圖片的方法
- Python列表刪除重復(fù)元素與圖像相似度判斷及刪除實(shí)例代碼
- 使用python如何刪除同一文件夾下相似的圖片
- python matplotlib繪圖實(shí)現(xiàn)刪除重復(fù)冗余圖例的操作
- python3 刪除所有自定義變量的操作
- python刪除csv文件的行列
- python讀寫刪除復(fù)制文件操作方法詳細(xì)實(shí)例總結(jié)
- Python 有可能刪除 GIL 嗎?
- Python中刪除文件的幾種方法實(shí)例
- 詳解Python遍歷列表時(shí)刪除元素的正確做法
- Python列表元素刪除和remove()方法詳解
- 教你怎么用python刪除相似度高的圖片
相關(guān)文章
Python獲取好友地區(qū)分布及好友性別分布情況代碼詳解
利用Python + wxpy 可以快速的查詢自己好友的地區(qū)分布情況,以及好友的性別分布數(shù)量。還可以批量下載好友的頭像,拼接成大圖。感興趣的朋友跟隨小編一起看看吧2019-07-07
使用Python實(shí)現(xiàn)為PDF文檔設(shè)置和移除密碼
在數(shù)字化時(shí)代,文檔的安全性變得越來越重要,特別是對(duì)于包含敏感信息的PDF文件,所以本文主要來和大家介紹一下如何使用Python實(shí)現(xiàn)為PDF文檔設(shè)置和移除密碼,需要的可以參考下2024-03-03
Python3.7實(shí)現(xiàn)中控考勤機(jī)自動(dòng)連接
這篇文章主要為大家詳細(xì)介紹了Python3.7實(shí)現(xiàn)中控考勤機(jī)自動(dòng)連接,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-08-08
python解析照片拍攝時(shí)間進(jìn)行圖片整理
這篇文章主要為大家介紹了python解析照片拍攝時(shí)間進(jìn)行圖片整理的示例源碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
基于django micro搭建網(wǎng)站實(shí)現(xiàn)加水印功能
這篇文章主要介紹了基于django micro搭建網(wǎng)站實(shí)現(xiàn)加水印功能,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05
python利用Opencv實(shí)現(xiàn)人臉識(shí)別功能
這篇文章主要為大家詳細(xì)介紹了python利用Opencv實(shí)現(xiàn)人臉識(shí)別功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-04-04
詳解Pytorch如何利用yaml定義卷積網(wǎng)絡(luò)
大多數(shù)卷積神經(jīng)網(wǎng)絡(luò)都是直接通過寫一個(gè)Model類來定義的,這樣寫的代碼其實(shí)是比較好懂,也很方便。但是本文將介紹另一個(gè)方法:利用yaml定義卷積網(wǎng)絡(luò),感興趣的可以了解一下2022-10-10

