elaz
elaz

Reputation: 3

invoke matplotlib toolbar keeping custom views history

I have a modified toolbar that has a button that zooms the x-axis by half on each click. I will show the code below. So, after click,click,click I realize I did one more zoom than desirable and would like to use the back button to view one-from-the-last. Had I done this zooming with the toolbar zoom button I would be able to do this. Since I zoomed by a different process this does not happen. So, I want my Zoomx to accumulate its history just as Matplotlib's zoom does. The code is below. Note that if the zoom-to-rectange is invoked the history is accumulated in the usual way. I ant my black-cloud button to do the same. There is a lot of literature suggesting there is a push_current procedure for doing this. Most of the suggestions fail. I am using python 3.12.4 with matplotlib 3.8.4. Depending on where this is run, the icon name and directory may need to be changed.

import matplotlib
matplotlib.rcParams["toolbar"] = "toolmanager"
import matplotlib.pyplot as plt
from matplotlib.backend_tools import ToolBase

class Zoomx(ToolBase):
    def plot_axes(self,f=None):
        print("f in:",f)
        slimx=self.canvas.figure.axes[0].get_xlim()
        slimy=self.canvas.figure.axes[0].get_ylim()
        qikday=slimx[1]-(slimx[1]-slimx[0])/f
        print("newlims:",([qikday,slimx[1]]))
        self.canvas.figure.axes[0].set_xlim([qikday,slimx[1]])
        self.canvas.draw()
        return
    #filedir is the location of the icon being added to toolbar
    icon="Icon.light.targetsize-44"    
    filedir="C:\Program Files\WindowsApps\\Microsoft.GamingApp_2412.1001.22.0_x64__8wekyb3d8bbwe\\XCloudPublicAssets\\Icons\\"
    handpng=filedir+icon
    print(f"{handpng:}")
    image = f"{handpng:}"

    default_keymap = 'z'  # Keyboard shortcut
    description = 'zoom-xaxis Tool'

    def trigger(self, *args, **kwargs):
        xyz=self.plot_axes(f=2) # each button click halves x-range from the left
        

        
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 2, 3], label="legend")
ax.legend()
tm = fig.canvas.manager.toolmanager
tm.add_tool("Zoomx", Zoomx)
fig.canvas.manager.toolbar.add_tool(tm.get_tool("Zoomx"), "toolgroup")
plt.show()

Upvotes: 0

Views: 20

Answers (0)

Related Questions