How to get correct xtick labels with zooming and panning

I ended up creating a wrapper around the toolbar and resetting the labels and redrawing whenever something changes. Is there a cleaner way?

class WrappedNavigationToolbar(NavigationToolbar):

def **__init__**(*self*, viewer, canvas, parent):

    *self*.viewer = viewer

    super(WrappedNavigationToolbar, *self*).__init__(canvas, parent)

   

def **release_zoom**(*self*, event):

    print *"release zoom"*

    super(WrappedNavigationToolbar, *self*).release_zoom(event)

    *self*.viewer.resetLabels()

    *self*.draw()

           

def **release_pan**(*self*, event):

    print *"release_pan"*

    super(WrappedNavigationToolbar, *self*).release_pan(event)

    *self*.viewer.resetLabels()

    *self*.draw()

   

def **home**(*self*, *args):

    print *"home"*       

    super(WrappedNavigationToolbar, *self*).home(*args)

    *self*.viewer.resetLabels()

    *self*.draw()

def **forward**(*self*, *args):

    print *"forward"*       

    super(WrappedNavigationToolbar, *self*).forward(*args)

    *self*.viewer.resetLabels()

    *self*.draw()

def **back**(*self*, *args):

    print *"back"*       

    super(WrappedNavigationToolbar, *self*).back(*args)

    *self*.viewer.resetLabels()

self.draw()

def **resetLabels**(*self*):

    xlabels = *self*.plotInfo.getXValues()

    xticks = *self*.axes.get_xticks()

    newticks = []

    for label in xticks:

        idx = int(label)

        if idx >=0 and idx < len(xlabels):

            newticks.append(xlabels[idx])

        else:

            newticks.append(*""*)

           

    *self*.axes.set_xticklabels(newticks)
···

From: Fiedler, Lars - 0447 - MITLL
Sent: Thursday, August 11, 2011 6:10 PM
To: matplotlib-users@lists.sourceforge.net
Cc: Fiedler, Lars - 0447 - MITLL
Subject: How to get correct xtick labels with zooming and panning

Hi,

If I create a bar graph inside a FigureCanvas, how do I get the correct x tick labels to display when someone does a zoom with the NavigationToolbar?

For example, lets say I’ve got the below code:

    *self*.axes.set_xticks = range(len(vals))

    *self*.axes.set_xticklabels(*xLabels*)

    *self*.axes.bar(

        left=range(len(vals)),

        height=map(float, vals),

        width=.2,

        align=*'center'*,

        alpha=0.44,

        picker=5)

If the number of values is very large, then matplotlib seems to select only a few x labels to display (selecting far left and right, and some in the middle), but it’s choosing the first ones in the specified label array, instead of indexing into it.

I’ve tried setting the tick labels, based on the ticks it’s selected, (setting labels based on the ticks after the bar has been created) and that seems to work on the initial load, but then if someone zooms into a particular part, it doesn’t update the labels to the correct range … It’s almost like I would need a callback to reset the labels …

Ideas?

Cheers,

Lars