In matplotlib, how do you display an axis on both sides of the figure?

前端 未结 3 1508
眼角桃花
眼角桃花 2020-12-16 12:32

I want to draw a plot with matplotlib with axis on both sides of the plot, similar to this plot (the color is irrelevant to this question):

相关标签:
3条回答
  • 2020-12-16 12:54

    You can use tick_params() (this I did in Jupyter notebook):

    import matplotlib.pyplot as plt
    
    bar(range(10), range(10))
    tick_params(labeltop=True, labelright=True)
    

    Generates this image:

    Bar plot with both x and y axis labeled the same

    UPD: added a simple example for subplots. You should use tick_params() with axis object.

    This code sets to display only top labels for the top subplot and bottom labels for the bottom subplot (with corresponding ticks):

    import matplotlib.pyplot as plt
    
    f, axarr = plt.subplots(2)
    
    axarr[0].bar(range(10), range(10))
    axarr[0].tick_params(labelbottom=False, labeltop=True, labelleft=False, labelright=False,
                         bottom=False, top=True, left=False, right=False)
    
    axarr[1].bar(range(10), range(10, 0, -1))
    axarr[1].tick_params(labelbottom=True, labeltop=False, labelleft=False, labelright=False,
                         bottom=True, top=False, left=False, right=False)
    

    Looks like this:

    Subplots ticks config example

    0 讨论(0)
  • 2020-12-16 13:01

    There are a couple of relevant examples in the online documentation:

    • Two Scales (seems to do exactly what you're asking for)
    • Dual Fahrenheit and Celsius
    0 讨论(0)
  • 2020-12-16 13:02

    I've done this previously using the following:

    # Create figure and initial axis    
    fig, ax0 = plt.subplots()
    # Create a duplicate of the original xaxis, giving you an additional axis object
    ax1 = ax.twinx()
    # Set the limits of the new axis from the original axis limits
    ax1.set_ylim(ax0.get_ylim())
    

    This will exactly duplicate the original y-axis.

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