I am new to python and am trying to plot multiple lines in the same figure using matplotlib. Value of my Y axis is stored in a dictionary and I make corresponding values in X axis in my following code

My code is like this:

for i in range(len(ID)):
AxisY= PlotPoints[ID[i]]
if len(AxisY)> 5:
    AxisX= [len(AxisY)]
    for i in range(1,len(AxisY)):
        AxisX.append(AxisX[i-1]-1)
    plt.plot(AxisX,AxisY)
    plt.xlabel('Lead Time (in days)')
    plt.ylabel('Proportation of Events Scheduled')
    ax = plt.gca()
    ax.invert_xaxis()
    ax.yaxis.tick_right()
    ax.yaxis.set_label_position("right")
    plt.show()

But i'm getting separate figures with one plot one by one What's the problem with my code? Why is it not possible to create multiline plots? Thanks very much

Best Answer


This is very simple

import matplotlib.pyplot as plt

plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.legend(loc='best')
plt.show()

You can keep adding plt.plot as many times as you like. As for line type , you need to first specify the color. So for blue, it's b . And for a normal line it's - . An example would be

plt.plot(total_lengths, sort_times_heap, 'b-', label="Heap")