Matplotlib change xticks and retain xticks changing during zoom

Hello,

I execute the following code:

try:
        from math import *
        import pylab as p
except:
        print "Couldn't import all dependent libraries"
        sys.exit()
dataLength = 100
data = [sin(2*pi*x/dataLength) for x in range(0,dataLength)]
p.plot(data)
p.show()

This produces a figure window. When I zoom in regions of the plot, the
xticks change correctly to the zoomed region.

This is in contrast to the effect of the following code:

try:
        from math import *
        import pylab as p
except:
        print "Couldn't import all dependent libraries"
        sys.exit()
dataLength = 100
data = [sin(2*pi*x/dataLength) for x in range(0,dataLength)]
p.plot(data)
newXTicks= [str(x/2.0) for x in p.xticks()[0]]
p.xticks(p.xticks()[0], newXTicks)
p.show()

This code produces tick marks [0, 10, 20, 30, 40, 50]. However when
zooming, the xtick marks do not adjust correctly to the zoomed
regions.

Your help on this issue would be great, thanks!

This is in contrast to the effect of the following code:

try:
       from math import *
       import pylab as p
except:
       print "Couldn't import all dependent libraries"
       sys.exit()
dataLength = 100
data = [sin(2*pi*x/dataLength) for x in range(0,dataLength)]
p.plot(data)
newXTicks= [str(x/2.0) for x in p.xticks()[0]]
p.xticks(p.xticks()[0], newXTicks)
p.show()

This code produces tick marks [0, 10, 20, 30, 40, 50]. However when
zooming, the xtick marks do not adjust correctly to the zoomed
regions.

Setting the tick locations explicitly means that you want the mpl to
stick to what you just provided and not to automatically adjust the
tick locations. And that's the behavior you're seeing.

Guessing from your code, it seems that you're fine with tick locations
but want to change the format of the tick label.

check the docmentation and also the example (custom_ticker1.py).

http://matplotlib.sourceforge.net/api/ticker_api.html

Here's what you may try:

from matplotlib.ticker import FuncFormatter

dataLength = 100
data = [sin(2*pi*x/dataLength) for x in range(0,dataLength)]
p.plot(data)

def label_half(x, pos):
    return str(x/2.)

gca().xaxis.set_major_formatter(FuncFormatter(label_half))
p.draw()
p.show()

-JJ