Search code examples
pythonmatplotlibzoomingaxis-labels

Is there a way to detect zoom in Matplotlib plots and set minor tick format according to zoom level?


I want to plot a large data range but have ability to zoom in and gain resolution. I need to use custom major and minor tick formatting therefore I lose the ability to have them set dynamically with the zoom level. Is there a practical solution to this problem?


Solution

  • You just need to create your own tick formatter and then attach it to the axes object.

    This example has everything you need. Essentially, create a function which takes the value of the tick, and returns what you would like the tick label to be - call it my_formatter, and then do this:

    ax.xaxis.set_major_formatter(ticker.FuncFormatter(my_formatter))
    

    and optionally

    ax.xaxis.set_minor_formatter(ticker.FuncFormatter(my_formatter))
    

    Where the ticker.FuncFormatter(my_function) creates the custom formatter for you.