Search code examples
pythonmatplotlibaxes

matplotlib get axis-relative tick positions


I know that I can get the positions of my y-ticks by ax.get_yticks() (btw., is that the best/correct way to get them?). But I need the tick positions relative to the axis limits (i.e., between 0 and 1). What is the best way to get that? I tried ax.get_yticks(transform=ax.transAxes), which does not work.


Solution

  • This transformation can be easily done by hand:

    y_min, y_max = ax.get_ylim()
    ticks = [(tick - y_min)/(y_max - y_min) for tick in ax.get_yticks()]
    

    UPDATE

    To get it working with log scales, we need to employ matplotlib.transforms. But transforms can only work with (x,y) points, so we need first to complement y-ticks with some x coordinates (for example, zeros):

    crd = np.vstack((np.zeros_like(ax.get_yticks()), ax.get_yticks())).T
    

    Then we can transform data coodinates to display and then to axes and take y column of it:

    ticks = ax.transAxes.inverted().transform(ax.transData.transform(crd))[:,1]