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

前端 未结 7 1553
遇见更好的自我
遇见更好的自我 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:53

    If you're using axis labels, Leo's solution can push them off the side, due to the precision of the numbers in the ticks.

    So in addition to something like Leo's solution (repeated here),

    ax2.set_yticks(np.linspace(ax2.get_yticks()[0],ax2.get_yticks()[-1],len(ax1.get_yticks())))
    

    you can use the autolayout setting, as mentioned in this answer; e.g., earlier in your script you can update rcParams:

    from matplotlib import rcParams
    rcParams.update({'figure.autolayout': True})
    

    In a few test cases, this appears to produce the expected result, with both lined-up ticks and labels fully contained in the output.

提交回复
热议问题