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 plot.
We can change the line width (line thickness) of lines in Python Matplotlib legend by using the set_linewidth() method of the legend object and the setp() method of the artist objects.
matplotlib.pyplot.plot(x, y, linewidth=1.5) By default, the line width is 1.5 but you can adjust this to any value greater than 0.
If you want to make the line width of a graph plot thinner, then you can make linewidth less than 1, such as 0.5 or 0.25. If you want to make the line width of the graph plot thicker, then you can make linewidth greater than 1. This thickens the graph plot.
Here's a simple example of how to do it:
import numpy as np import matplotlib.pyplot as plt # make some data x = 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 plots leg = plt.legend([p1, p2], ['sin(x)', 'cos(x)'], loc=1) # set the linewidth of each legend object for 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 np import matplotlib.pyplot as plt # make some data x = 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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With