Matplotlib - imshow twiny() problems

前端 未结 1 1119
栀梦
栀梦 2021-01-14 04:38

I am trying to have two inter-depedent x-axis in a matplotlib imshow() plot. I have bottom x-axis as the radius squared and I want the top as just the radius. I have tried s

相关标签:
1条回答
  • 2021-01-14 05:31

    You're misunderstanding what twiny does. It makes a completely independent x-axis with a shared y-axis.

    What you want to do is have a different formatter with a linked axis (i.e. sharing the axis limits but nothing else).

    The simple way to do this is to manually set the axis limits for the twinned axis:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.ticker import FuncFormatter
    
    fig, ax1 = plt.subplots()
    ax1.plot(range(10))
    
    ax2 = ax1.twiny()
    formatter = FuncFormatter(lambda x, pos: '{:0.2f}'.format(np.sqrt(x)))
    ax2.xaxis.set_major_formatter(formatter)
    
    ax2.set_xlim(ax1.get_xlim())
    
    plt.show()
    

    enter image description here

    However, as soon as you zoom or interact with the plot, you'll notice that the axes are unlinked.

    You could add an axes in the same position with both shared x and y axes, but then the tick formatters are shared, as well.

    Therefore, the easiest way to do this is using a parasite axes.

    As a quick example:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.ticker import FuncFormatter
    from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost
    
    fig = plt.figure()
    ax1 = SubplotHost(fig, 1,1,1)
    fig.add_subplot(ax1)
    
    ax2 = ax1.twin()
    
    ax1.plot(range(10))
    
    formatter = FuncFormatter(lambda x, pos: '{:0.2f}'.format(np.sqrt(x)))
    ax2.xaxis.set_major_formatter(formatter)
    
    plt.show()
    

    Both this and the previous plot will look identical at first. The difference will become apparent when you interact (e.g. zoom/pan) with the plot.

    0 讨论(0)
提交回复
热议问题