Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

manipulate linestyle in matplotlib legend

I would like to include a legend in my plot, which shows all lines as solid line even if the corresponding curve uses linstyle '--'. Is there

plt.plot(x, y, linestyle='--')
plt.legend(loc=0) 
plt.show()

So the legend for the plot above should show one solid line.

like image 421
carl Avatar asked Sep 03 '25 09:09

carl


1 Answers

You can explicitly tell ax.legend what to show and what not. Using a separate Line2D object (see here) you can make the line in the legend solid even though the plotted line is dashed. Here is a working example:

from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
import numpy as np


fig, ax = plt.subplots()
x = np.linspace(0,2*np.pi,100)
y = np.sin(x)
ax.plot(x,y,'r--')
line = Line2D([0,1],[0,1],linestyle='-', color='r')

ax.legend([line],['solid line'])

plt.show()

and the result looks like this:

result of the above code

like image 183
Thomas Kühn Avatar answered Sep 04 '25 23:09

Thomas Kühn