Search code examples
pythonmatplotlibline-plot

Create 2 line plots in the same figure with common y range Python


I would like to make a 2 line plots in the same plot:

import matplotlib.pyplot as plt

x1 = [0.53884, 0.53878, 0.53898, 0.53662, 0.53748, 0.5398, 0.53894, 0.53732, 0.53744, 0.54052, 0.54402, 0.54178] 
x2 = [54.9, 54.9, 54.9, 54.9, 54.9, 54.9, 54.9, 54.9, 54.9, 54.9, 54.9, 54.9]

x = range(len(x1))

top_lim = max( max(x1), max(x2) ) + 0.001
bottom_lim = min( min(x1), min(x2) ) - 0.001
plt.ylim(bottom_lim, top_lim)

plt.plot(x, x1)
plt.plot(x, x2 ,color='r')

plt.show()

However, this gives me a blank figure. How can I get the correct plot?


Solution

  • So the problem in your code is the ylim you can try the following:

    import matplotlib.pyplot as plt
    
    x1 = [0.53884, 0.53878, 0.53898, 0.53662, 0.53748, 0.5398, 0.53894, 0.53732, 0.53744, 0.54052, 0.54402, 0.54178]
    x2 = [54.9, 54.9, 54.9, 54.9, 54.9, 54.9, 54.9, 54.9, 54.9, 54.9, 54.9, 54.9]
    
    x = list(range(len(x1)))
    
    top_lim = max( max(x1), max(x2) ) + 5
    bottom_lim = min( min(x1), min(x2) ) - 5
    plt.ylim(bottom_lim, top_lim)
    
    plt.plot(x, x1)
    plt.plot(x, x2 ,color='r')
    
    plt.show()
    

    Due to the fact the values between x1,x2 then both line where at the edges of the plot thus you could not see it.