Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Legend with vertical line in matplotlib

I need to show a vertical line in a matplotlib legend for a specific reason. I am trying to make matplotlib understand that I want a vertical line with the lines.Line2D(x,y) but this is clearly not working.

import matplotlib.pyplot as plt
from matplotlib import lines
fig, ax = plt.subplots()
ax.plot([0,0],[0,3])
lgd = []
lgd.append(lines.Line2D([0,0],[0,1], color = 'blue', label = 'Vertical line'))
plt.legend(handles = lgd)

enter image description here

I need the line to appear vertical, not the legend. Can anyone help?

like image 409
Joaquim Villén Avatar asked Nov 02 '18 16:11

Joaquim Villén


People also ask

How do I change the position of a legend in Matplotlib?

To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.


1 Answers

You can use the vertical line marker when making your line2D object. A list of valid markers can be found here.

import matplotlib.pyplot as plt
from matplotlib import lines

fig, ax = plt.subplots()
ax.plot([0,0],[0,3])

vertical_line = lines.Line2D([], [], color='#1f77b4', marker='|', linestyle='None',
                          markersize=10, markeredgewidth=1.5, label='Vertical line')

plt.legend(handles = [vertical_line])

plt.show()

enter image description here

like image 148
DavidG Avatar answered Sep 19 '22 08:09

DavidG