increase the linewidth of the legend lines in matplotlib

前端 未结 4 972
说谎
说谎 2020-12-01 03:53

I know that if I change the linewidth of a line, that is automatically updated in the legend. However I would like to just change the legend linewidth without affecting the

4条回答
  •  鱼传尺愫
    2020-12-01 04:31

    By default, the legend contains the lines themselves. Therefore changing the linewidth of the lines in the canvas will also change the lines in the legend (and vice versa, as they are essentially the same object).

    A possible solution is to use a copy of the artist from the canvas and change only the copy's linewidth.

    import numpy as np
    import matplotlib.pyplot as plt
    import copy
    
    x = np.linspace(0, 2*np.pi)
    y1 = np.sin(x)
    y2 = np.cos(x)
    fig = plt.figure()
    ax  = fig.add_subplot(111)
    ax.plot(x, y1, c='b', label='y1',linewidth=1.0)
    ax.plot(x, y2, c='r', label='y2')
    
    # obtain the handles and labels from the figure
    handles, labels = ax.get_legend_handles_labels()
    # copy the handles
    handles = [copy.copy(ha) for ha in handles ]
    # set the linewidths to the copies
    [ha.set_linewidth(7) for ha in handles ]
    # put the copies into the legend
    leg = plt.legend(handles=handles, labels=labels)
    
    plt.savefig('leg_example')
    plt.show()
    

    A different option would be to use a handler_map and an updating function. This is somehow automatic, specifying the handler map would automatically make any line in the legend 7 points wide.

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.legend_handler import HandlerLine2D
    
    x = np.linspace(0, 2*np.pi)
    y1 = np.sin(x)
    y2 = np.cos(x)
    fig = plt.figure()
    ax  = fig.add_subplot(111)
    ax.plot(x, y1, c='b', label='y1',linewidth=1.0)
    ax.plot(x, y2, c='r', label='y2')
    
    linewidth=7
    def update(handle, orig):
        handle.update_from(orig)
        handle.set_linewidth(7)
    
    plt.legend(handler_map={plt.Line2D : HandlerLine2D(update_func=update)})
    
    plt.show()
    

    The result is the same as above.

提交回复
热议问题