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)
I need the line to appear vertical, not the legend. Can anyone help?
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.
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()
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