user11607046
user11607046

Reputation: 197

Adding legends in Python matplotlib

I have generated a plot with multiple line using a for loop. But I cannot add a legend to this graph. Below is the code I have tried.

for l in range(3,8,1):
     seq=np.arange(0,20)
     X=stats.poisson(l)
     seq_pmf = X.pmf(seq)
     plt.plot(seq, seq_pmf,label=l)

I want the legend labels as λ=3, λ=4...like wise

Upvotes: 1

Views: 1579

Answers (2)

Alex
Alex

Reputation: 1126

like this?

for l in range(3,8,1):
    seq=np.arange(0,20)
    X=stats.poisson(l)
    seq_pmf = X.pmf(seq)
    plt.plot(seq, seq_pmf,label=r'$\lambda$ = '+str(l))
    plt.legend()

enter image description here

Upvotes: 1

Yaron Grushka
Yaron Grushka

Reputation: 233

You need to add plt.legend() before showing the graph.

e.g:

for l in range(3,8,1):
     seq=np.arange(0,20)
     X=stats.poisson(l)
     seq_pmf = X.pmf(seq)
     plt.plot(seq, seq_pmf,label=l)
plt.legend()
plt.show()

Upvotes: 1

Related Questions