Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increase the linewidth of the legend lines in matplotlib

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.

like image 254
Andrea Zonca Avatar asked Mar 14 '12 17:03

Andrea Zonca


People also ask

How do you change linewidth in legend Matplotlib?

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.

How do I make lines thicker in Matplotlib?

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.

How do you increase the thickness of a line in Python?

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.


2 Answers

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() 
like image 129
Brendan Wood Avatar answered Sep 23 '22 18:09

Brendan Wood


@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, enter image description here

like image 30
jdhao Avatar answered Sep 24 '22 18:09

jdhao