How to make two markers share the same label in the legend using matplotlib?

前端 未结 5 1305
抹茶落季
抹茶落季 2020-12-28 18:41

What I want is like this: \"enter

What I get is this:

5条回答
  •  既然无缘
    2020-12-28 19:12

    You can do this by plotting data without any label and then adding the label separately:

    from matplotlib import pyplot as plt
    from numpy import random
    
    xs = range(10)
    data = random.rand(10, 2)    
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    kwargs = {'color': 'r', 'linewidth': 2, 'linestyle': '--'}
    
    ax.plot(xs, data, **kwargs)
    ax.plot([], [], label='Model', **kwargs)
    ax.legend()
    plt.show()
    

提交回复
热议问题