Pyplot: show only first 3 lines in legend

Viewed 14794

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()
3 Answers

You could also just revise the arguments to plt.legend() as follows, and all but the first three legend entries will be hidden:

plt.legend(['susceptible', 'recovered', 'infected'])
Related