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

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

What I want is like this: \"enter

What I get is this:

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-28 18:50

    Note that in recent versions of matplotlib you can achieve this using class matplotlib.legend_handler.HandlerTuple as illustrated in this answer and also in this guide:

    import matplotlib.pyplot as plt
    from matplotlib.legend_handler import HandlerTuple
    fig, ax1 = plt.subplots(1, 1)
    
    # First plot: two legend keys for a single entry
    p2, = ax1.plot([3, 4], [2, 3], 'o', mfc="white", mec="k")
    p1, = ax1.plot([1, 2], [5, 6], 's', mfc="gray", mec="gray")
    # `plot` returns a list, but we want the handle - thus the comma on the left
    p3, = ax1.plot([1, 5], [4, 4], "-k")
    p4, = ax1.plot([2, 6], [3, 2], "-k")
    
    # Assign two of the handles to the same legend entry by putting them in a tuple
    # and using a generic handler map (which would be used for any additional
    # tuples of handles like (p1, p3)).
    l = ax1.legend([(p1, p2), p3], ['data', 'models'],
                   handler_map={tuple: HandlerTuple(ndivide=None)})
    
    plt.savefig("demo.png")
    

提交回复
热议问题