increase the linewidth of the legend lines in matplotlib increase the linewidth of the legend lines in matplotlib python python

increase the linewidth of the legend lines in matplotlib


Here's a simple example of how to do it:

import numpy as npimport matplotlib.pyplot as plt# make some datax = np.linspace(0, 2*np.pi)y1 = np.sin(x)y2 = np.cos(x)# plot sin(x) and cos(x)p1 = plt.plot(x, y1, 'b-', linewidth=1.0)p2 = plt.plot(x, y2, 'r-', linewidth=1.0)# make a legend for both plotsleg = plt.legend([p1, p2], ['sin(x)', 'cos(x)'], loc=1)# set the linewidth of each legend objectfor legobj in leg.legendHandles:    legobj.set_linewidth(2.0)plt.show()


@Brendan Wood's method use the api provided by pyplot. In matplotlib, the object oriented style using axes is prefered. The following is how you can achieve this using axes method.

import numpy as npimport matplotlib.pyplot as plt# make some datax = np.linspace(0, 2*np.pi)y1 = np.sin(x)y2 = np.cos(x)fig, ax = plt.subplots()ax.plot(x, y1, linewidth=1.0, label='sin(x)')ax.plot(x, y2, linewidth=1.0, label='cos(x)')leg = ax.legend()for line in leg.get_lines():    line.set_linewidth(4.0)plt.show()

The produced plot is shown below,enter image description here


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 npimport matplotlib.pyplot as pltimport copyx = 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 figurehandles, labels = ax.get_legend_handles_labels()# copy the handleshandles = [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 legendleg = plt.legend(handles=handles, labels=labels)plt.savefig('leg_example')plt.show()

enter image description here

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 npimport matplotlib.pyplot as pltfrom matplotlib.legend_handler import HandlerLine2Dx = 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=7def 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.