How to plot the legend of this graph of which there are many functions?

Viewed 135

I have a matrix X contains only 1 row that serves as an input. I have a matrix Y of which each row serves as an output of a function. If Y has 5 rows, then we have 5 different functions. I plot all functions on the same graph with the following code:

import numpy as np
import matplotlib
import matplotlib.pyplot as plt

Y = np.random.randint(1, 9, size = (5, 7))
X = np.arange(- 3, 4)

fig, ax = plt.subplots()
for i in range(5):
    ax.plot(X, Y[i])

and its result

enter image description here

I would like ask how to add the legend of this graph. My desire format is

n = 0: color 0
n = 1: color 1
n = 2: color 2
n = 3: color 3
n = 4: color 4
n = 5: color 5

Thank you so much for your help!

1 Answers

I would say this is the way:

for i in range(5):
    ax.plot(X, Y[i], label = i)

plt.legend()

which makes this plot:

enter image description here

But I am asking myself if it is what you are looking for.

Related