1

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

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

3 Comments

Yes. But how can I get it as, λ=3, λ=4...like wise. Instead of just the λ value?
In the label argument you can specify label="$\lambda$=l".
Oh, right. You can use f-string: label=f'$\lambda$ = {l}'
1

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

2 Comments

plt.plot(seq, seq_pmf,label="λ={0}".format(l)) This works!
right. it almost the same. The difference only is how you create this final label string: explicitly use greek lambda-symbol or it code

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.