matplotlibtwinx

position setting for scientific notation on coordinate axis


Normally when I plot a figure with double y-axis using pyplot, I use

ax2.yaxis.tick_right()

to place ticks of ax2 to right for visual clarity, however, I found pyplot automatically show value in scientific notation when value range on axis is big enough, e.g., 1.6e7, and that makes '1e7' placed on top of right axis, rather than right side like rest of ticks and number. Honestly I don't even know how to describe it as it looks like not part of tick or notation. Example figure can be seen here:

here

A potential solution is prevent pyplot using scientific notation but I prefer to keep it. So how can I set it (in this case '1e7') to right side of second(right) axis? Thanks


Solution

  • I think what you are asking to do is move the offset text (the orange 1e7) towards the right on your plot.

    Currently, your offset text is set to a position of 1 in the x-direction (in Axes coordinates), with a horizontal alignment of "right" (i.e. the right edge of the text is aligned with the coordinate 1).

    We can move the x coordinate of the text, by first getting a reference to the offset text instance using ax2.yaxis.get_offset_text(), and then call the set_x method on that text. You may also wish to set the horizontal alignment of the text (e.g. setting this to "left" and the coordinate to 1 will align with the outer edge of the Axes).

    See this minimal example for how to do this. You will probably want to play around with the X coordinate to suit your needs.


    Without moving the offset text:

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    ax2 = ax.twinx()
    
    ax2.plot([0, 1.6e7])
    plt.show()
    

    Original image, with no offset


    Setting the horizontal alignment to "left" and the position to 1:

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots(figsize=(5, 3))
    ax2 = ax.twinx()
    
    ax2.plot([0, 1.6e7])
    offsetText = ax2.yaxis.get_offset_text()
    offsetText.set_horizontalalignment('left')
    offsetText.set_x(1)
    
    plt.show()
    

    Setting the horizontal alignment to "left" and the position to 1


    Moving the text a little more to the right:

    offsetText.set_x(1.05)
    

    Moving the text a little more to the right