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

后端 未结 2 756
南方客
南方客 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:24

    Here is one possible solution: You may use the fact that underscores do not produce legend entries. So setting all but the first label to "_" suppresses those to appear in the legend.

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, ax = plt.subplots()
    
    x = np.array([[0,1], [0,1], [0,1]])
    y = np.array([[0,0], [1,1], [2,2]])
    
    ax.plot([0,1],[0,2], label='foo', color='b')
    
    lines = ax.plot(x.T, y.T, label='bar', color='k')
    plt.setp(lines[1:], label="_")
    ax.legend()
    
    plt.show()
    

    0 讨论(0)
  • 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()
    

    0 讨论(0)
提交回复
热议问题