Matplotlib axis with two scales shared origin

前端 未结 7 1374
忘了有多久
忘了有多久 2020-11-29 04:17

I need two overlay two datasets with different Y-axis scales in Matplotlib. The data contains both positive and negative values. I want the two axes to share one origin, but

7条回答
  •  日久生厌
    2020-11-29 04:44

    The other answers here seem overly complicated and don't necessarily work for all the scenarios (e.g. ax1 is all negative and ax2 is all positive). There are 2 easy methods that always work:

    1. Always put 0 in the middle of the graph for both y axes
    2. A bit fancy and somewhat preserves the positive-to-negative ratio, see below
    def align_yaxis(ax1, ax2):
        y_lims = numpy.array([ax.get_ylim() for ax in [ax1, ax2]])
    
        # force 0 to appear on both axes, comment if don't need
        y_lims[:, 0] = y_lims[:, 0].clip(None, 0)
        y_lims[:, 1] = y_lims[:, 1].clip(0, None)
    
        # normalize both axes
        y_mags = (y_lims[:,1] - y_lims[:,0]).reshape(len(y_lims),1)
        y_lims_normalized = y_lims / y_mags
    
        # find combined range
        y_new_lims_normalized = numpy.array([numpy.min(y_lims_normalized), numpy.max(y_lims_normalized)])
    
        # denormalize combined range to get new axes
        new_lim1, new_lim2 = y_new_lims_normalized * y_mags
        ax1.set_ylim(new_lim1)
        ax2.set_ylim(new_lim2)
    

提交回复
热议问题