Search code examples
matplotlibintervalssubplot

How to draw lines based on intervals in matplotlib?


I have these three lists

odds = [1,3,5,7,9]
evens = [2,4,6,8,10]
all_nums = [2,1,4,3,6,5,8,7,10,9]

I need to first draw a line showing the values in all_nums, and then draw the other two lines that connect the values in odds and evens.

For example, after I first draw the line of all_nums, I got enter image description here

And my final expected graph should be enter image description here

I am not sure how to draw the red and green lines as they are produced based on an "interval 2" on the x-axis with respect to the blue line.

I have created a repl.it with my current code.

Note, my real project is more complicated than this example, in which the first line looks like enter image description here And I need to connect all the valley points and all the peak points, so I cannot simply apply tricks like changing odds = [1,3,5,7,9] to odds = [1,2,3,4,5,6,7,8,9,10] when drawing, as I wish the curve can also be smooth in the connection between points.

Thank you for your help!


Solution

  • I did something like this for the even and odd lines. odd looks 1:1 and even looks like y-2.

    odds = [1,3,5,7,9]
    evens = [2,4,6,8,10]
    all_nums = [2,1,4,3,6,5,8,7,10,9]
    even_sep=[]
    odd_sep=[]
    plt.plot(range(len(all_nums)), all_nums, label='odds and evens')
    for draw_num_iter in range(len(all_nums)):
      draw_num = all_nums[draw_num_iter]
      plt.annotate(draw_num, xy=(draw_num_iter, draw_num), size=20)
    for i in range(len(evens)):
      even_sep.append(evens[i]-2)
    plt.plot(even_sep,evens,'ro-')
    for i in range(len(odds)):
      odd_sep.append(odds[i])
    plt.plot(odd_sep,odds,'g')  
    plt.legend(loc='best')
    plt.show()