Secondary axis disposed Matplotlib

Original Address

Categories --Matplotlib

Sometimes there may be such a demand, a different range of y-axis of FIG several lines, or is not a unit, additional time may be added a y-axis, labeled on a different scale.

  • Look at the effect

    1582078480634

  • Import Support Package

    import matplotlib.pyplot as plt
    import numpy as np
    
  • Generate test data

    x = np.arange(0, 10, 0.1)
    y1 = 0.05 * x**2
    y2 = -1 * y1
    
  • Generating canvas

    fig, ax1 = plt.subplots()
    
  • A common x-axis

    ax2 = ax1.twinx()
    
  • Paint

    ax1.set_xlabel('X data')
    # 画基于左轴的曲线
    ax1.plot(x, y1, 'g-')   # green, solid line
    ax1.set_ylabel('Y1 data', color='g')
    # 画基于右轴的曲线
    ax2.plot(x, y2, 'b--') # blue, dashed line
    ax2.set_ylabel('Y2 data', color='b')
    # 出图
    plt.show()
    

    The results showing the text of the first shown in FIG.

  • Similarly you can share a y-axis, the x-axis even times

    y = np.arange(0, 10, 0.1)
    x1 = 0.05 * y**2
    x2 = -1 * x1
    
    fig, ax1 = plt.subplots()
    
    ax2 = ax1.twiny()
    
    ax1.set_ylabel('Y data')
    
    ax1.plot(x1, y, 'g-')   # green, solid line
    ax1.set_xlabel('X1 data', color='g')
    
    ax2.plot(x2, y, 'b--') # blue, dashed line
    ax2.set_xlabel('X2 data', color='b')
    
    plt.show()
    

    As shown in FIG.

    1582079157613

  • references

    The main program from the secondary axis , with slight changes

Published 119 original articles · won praise 86 · views 5843

Guess you like

Origin blog.csdn.net/BBJG_001/article/details/104454783