One legend entry when plotting several curves using one `plot` call

后端 未结 2 755
南方客
南方客 2021-01-21 13:54

I am creating a grid by plotting several curves using one plot call as:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-21 14:40

    Following is one way using the already existing legend handles and labels. You first get the three handles, labels and then just show the first one. This way additionally gives you a control not only on the order of putting handles but also what to show on the plot.

    ax.plot(x.T, y.T,  label='bar', color='k')
    handles, labels = ax.get_legend_handles_labels()
    ax.legend([handles[0]], [labels[0]], loc='best')
    

    Alternative approach where the legends will only be taken from a particular plot (set of lines) -- ax1 in this case

    ax1 = ax.plot(x.T, y.T,  label='bar', color='k')
    plt.legend(handles=[ax1[0]], loc='best')
    

    Extending it to you problem with two figures

    ax1 = ax.plot([0,1],[0,2], label='foo', color='b')
    ax2 = ax.plot(x.T, y.T,  label='bar', color='k')
    plt.legend(handles=[ax1[0], ax2[1]], loc='best')
    

    Another alternative using for loops as suggested by @SpghttCd

    for i in range(len(x)):
        ax.plot(x[i], y[i], label=('' if i==0 else '_') + 'bar', color='k')
    
    ax.legend()
    

提交回复
热议问题