two (or more) graphs in one plot with different x-axis AND y-axis scales in python

前端 未结 3 2008
刺人心
刺人心 2020-12-13 21:23

I want 3 graphs on one axes object, for example:

#example x- and y-data
x_values1=[1,2,3,4,5]
y_values1=[1,2,3,4,5]

x_values2=[-1000,-800,-600,-400,-200]
y_         


        
3条回答
  •  生来不讨喜
    2020-12-13 22:08

    You could also standardize the data so it shares the same limits and then plot the limits of the desired second scale "manually". This function standardizes the data to the limits of the first set of points:

    def standardize(data):
        for a in range(2):
            span = max(data[0][a]) - min(data[0][a])
            min_ = min(data[0][a])
            for idx in range(len(data)):
                standardize = (max(data[idx][a]) - min(data[idx][a]))/span
                data[idx][a] = [i/standardize + min_ - min([i/standardize 
                                for i in data[idx][a]]) for i in data[idx][a]]
        return data
    

    Then, plotting the data is easy:

    import matplotlib.pyplot as plt
    data = [[[1,2,3,4,5],[1,2,2,4,1]], [[-1000,-800,-600,-400,-200], [10,20,39,40,50]], [[150,200,250,300,350], [10,20,30,40,50]]]
    limits = [(min(data[1][a]), max(data[1][a])) for a in range(2)]
    
    norm_data = standardize(data)
    
    fig, ax = plt.subplots()
    
    for x, y in norm_data:
        ax.plot(x, y)
    
    ax2, ax3 = ax.twinx(), ax.twiny()
    ax2.set_ylim(limits[1])
    ax3.set_xlim(limits[0])
    
    plt.show()
    

    Since all data points have the limits of the first set of points, we can just plot them on the same axis. Then, using the limits of the desired second x and y axis we can set the limits for these two.

提交回复
热议问题