How do I align gridlines for two y-axis scales using Matplotlib?

前端 未结 7 1551
遇见更好的自我
遇见更好的自我 2020-11-29 00:16

I\'m plotting two datasets with different units on the y-axis. Is there a way to make the ticks and gridlines aligned on both y-axes?

The first image shows what I ge

7条回答
  •  醉梦人生
    2020-11-29 00:54

    I wrote this function that takes Matplotlib axes objects ax1, ax2, and floats minresax1 minresax2:

    def align_y_axis(ax1, ax2, minresax1, minresax2):
        """ Sets tick marks of twinx axes to line up with 7 total tick marks
    
        ax1 and ax2 are matplotlib axes
        Spacing between tick marks will be a factor of minresax1 and minresax2"""
    
        ax1ylims = ax1.get_ybound()
        ax2ylims = ax2.get_ybound()
        ax1factor = minresax1 * 6
        ax2factor = minresax2 * 6
        ax1.set_yticks(np.linspace(ax1ylims[0],
                                   ax1ylims[1]+(ax1factor -
                                   (ax1ylims[1]-ax1ylims[0]) % ax1factor) %
                                   ax1factor,
                                   7))
        ax2.set_yticks(np.linspace(ax2ylims[0],
                                   ax2ylims[1]+(ax2factor -
                                   (ax2ylims[1]-ax2ylims[0]) % ax2factor) %
                                   ax2factor,
                                   7))
    

    It calculates and sets the ticks such that there are seven ticks. The lowest tick corresponds to the current lowest tick and increases the highest tick such that the separation between each tick is integer multiples of minrexax1 or minrexax2.

    To make it general, you can set the total number of ticks you want by changing ever 7 you see to the total number of ticks, and change 6 to the total number of ticks minus 1.

    I put a pull request in to incorporate some this into matplotlib.ticker.LinearLocator:

    https://github.com/matplotlib/matplotlib/issues/6142

    In the future (Matplotlib 2.0 perhaps?), try:

    import matplotlib.ticker
    nticks = 11
    ax1.yaxis.set_major_locator(matplotlib.ticker.LinearLocator(nticks))
    ax2.yaxis.set_major_locator(matplotlib.ticker.LinearLocator(nticks))
    

    That should just work and choose convenient ticks for both y-axes.

提交回复
热议问题