Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyplot: show only first 3 lines in legend

I'm running a simulation 200 times and plotting the 3 output lists as 3 lines with high transparency. This allows me to show variance between simulations.

The problem is that my legend shows 3x200 items instead of 3 items. How do I get it to show the legend for each line once?

for simulation in range(200):  
    plt.plot(num_s_nodes, label="susceptible", color="blue", alpha=0.02)  
    plt.plot(num_r_nodes, label="recovered", color="green", alpha=0.02)
    plt.plot(num_i_nodes, label="infected", color="red", alpha=0.02)
plt.legend()  
plt.show()
like image 632
Alexis Eggermont Avatar asked Dec 16 '13 22:12

Alexis Eggermont


1 Answers

add

plt.plot( ... , label='_nolegend_')

for any plotting that you do not want to show up in the legend. so in your code you may for example do:

..., label='_nolegend_' if simulation else 'susceptible', ...

and similarly for others, or if you do not like iffy code:

..., label=simulation and '_nolegend_' or 'susceptible',...
like image 119
behzad.nouri Avatar answered Sep 28 '22 03:09

behzad.nouri