Search code examples
pythonmatplotlibtwinx

matplotlib twinx() 2nd axis markers on the same left axis


Say I create a secondary y-axis with twinx() similar to this demo

Is there a way I can place the tick marks and values of the secondary y-axis on the left side immediately next to the existing y-axis such as below ?

enter image description here


Solution

  • With the most recent versions of Matplotlib, this is pretty straightforward.

    def add_twin(ax, **kwargs):
        twin = ax.twinx()
        twin.yaxis.tick_left()
        twin.tick_params(axis='y', direction='in', **kwargs)
        for tick in twin.get_yticklabels():
            tick.set_horizontalalignment('right')
        return twin
    
    
    fig, ax = plt.subplots()
    twin = add_twin(ax)
    twin.set_yticks((0.1, 0.5, 0.9))
    

    The horizontal alignment part is key, and you'll probably need to tweak the pad for your purposes, using the kwargs. But you should get something like this:

    enter image description here