matplotlib align twinx tick marks

前端 未结 3 1116
小鲜肉
小鲜肉 2020-12-09 09:24

Is it possible to make a plot with two independent y-axes such that the tick marks align?

Below is an example of half of the solution. I\'ve doubled the y-axis using

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 10:06

    I know this is old, but this might help some people in the future.

    I made a function based on the solution above that makes sure that the labels don't end up to be something with a lot of decimals:

    def calculate_ticks(ax, ticks, round_to=0.1, center=False):
        upperbound = np.ceil(ax.get_ybound()[1]/round_to)
        lowerbound = np.floor(ax.get_ybound()[0]/round_to)
        dy = upperbound - lowerbound
        fit = np.floor(dy/(ticks - 1)) + 1
        dy_new = (ticks - 1)*fit
        if center:
            offset = np.floor((dy_new - dy)/2)
            lowerbound = lowerbound - offset
        values = np.linspace(lowerbound, lowerbound + dy_new, ticks)
        return values*round_to
    

    Which is used the following way:

    ax1.set_yticks(calculate_ticks(ax1, 10))
    ax2.set_yticks(calculate_ticks(ax2, 10))
    

    Output:

提交回复
热议问题