pythonmatplotlib

Change marker in the legend in matplotlib


Suppose that you plot a set of data:

plt.plot(x,y, marker='.', label='something')
plt.legend()

On the display, you will obtain . something, but how do you do to change it to - something, so that the marker that appears in the legend is a line a not a dot?


Solution

  • The solution surely depends on the criterion by which you want to transform the marker. Doing this manually is straight forward:

    import matplotlib.pyplot as plt
    
    line, = plt.plot([1,3,2], marker='o', label='something')
    plt.legend(handles = [plt.plot([],ls="-", color=line.get_color())[0]],
               labels=[line.get_label()])
    
    plt.show()
    

    enter image description here

    Doing the same in an automated way, i.e. each line in the plot gets its corresponding legend handle, which is a line in the same color, but without markers:

    import matplotlib.pyplot as plt
    from matplotlib.legend_handler import HandlerLine2D
    
    plt.plot([1,3,2], marker='o', label='something')
    plt.plot([2,3,3], marker='o', label='something else')
    
    def update_prop(handle, orig):
        handle.update_from(orig)
        handle.set_marker("")
    
    plt.legend(handler_map={plt.Line2D:HandlerLine2D(update_func=update_prop)})
    
    plt.show()
    

    enter image description here