I want to add an icon to a custom button in a matplotlib figure toolbar. How can I do that? So far, I have the following code:
JavaScript
x
16
16
1
import matplotlib
2
matplotlib.rcParams["toolbar"] = "toolmanager"
3
import matplotlib.pyplot as plt
4
from matplotlib.backend_tools import ToolToggleBase
5
6
class NewTool(ToolToggleBase):
7
tool code] [
8
9
fig = plt.figure()
10
ax = fig.add_subplot(111)
11
ax.plot([1, 2, 3], label="legend")
12
ax.legend()
13
fig.canvas.manager.toolmanager.add_tool("newtool", NewTool)
14
fig.canvas.manager.toolbar.add_tool(toolmanager.get_tool("newtool"), "toolgroup")
15
fig.show()
16
For now, the only thing that it does is adding a new button (which do what I want) but the icon is only the tool’s name i.e.: “newtool”. How can I change this for a custom icon like a png image?
Advertisement
Answer
The tool can have an attribute image
, which denotes the path to a png image.
JavaScript
1
17
17
1
import matplotlib
2
matplotlib.rcParams["toolbar"] = "toolmanager"
3
import matplotlib.pyplot as plt
4
from matplotlib.backend_tools import ToolBase
5
6
class NewTool(ToolBase):
7
image = r"C:pathtohiker.png"
8
9
fig = plt.figure()
10
ax = fig.add_subplot(111)
11
ax.plot([1, 2, 3], label="legend")
12
ax.legend()
13
tm = fig.canvas.manager.toolmanager
14
tm.add_tool("newtool", NewTool)
15
fig.canvas.manager.toolbar.add_tool(tm.get_tool("newtool"), "toolgroup")
16
plt.show()
17