Dax Feliz
Dax Feliz

Reputation: 12899

Making a custom vertical line marker in legend with matplotlib

I have a figure with a lot of horizontal lines, each with its own label. I also have a few vertical lines with labels as well. By default, pyplot.legend() shows these labels with horizontal line markers and I want to visually differentiate my vertical line labels from my horizontal line labels. Are there any ideas on how to do this? Below is a simple command to plot a line.

plt.axvline( x=10, linestyle='-',color='black',label='vertical line')
plt.legend()

enter image description here

Also:

I'm aware of this suggestion at Legend with vertical line in matplotlib but I am not sure how to implement it for a single label in the legend.

Upvotes: 2

Views: 4701

Answers (1)

Sheldore
Sheldore

Reputation: 39042

Here is one way to do it for multiple vertical legends. I chose very simple data to provide a working solution. You can extend the concept to your actual data

from matplotlib import lines

fig, ax = plt.subplots()

plt.plot([0, 5], [1, 1], label='y=1')
plt.plot([0, 5], [2, 2], label='y=2')
plt.plot([0, 5], [3, 3], label='y=3')

handles, _  = ax.get_legend_handles_labels()

vertical_pos = [5, 7, 10]
colors = ['r', 'g', 'b']

for x, c in zip(vertical_pos, colors):
    plt.plot([x, x], [0, 3], color=c, label='Vertical x=%s' %x)

_, labels = ax.get_legend_handles_labels()

for c in colors:
    vertical_line = lines.Line2D([], [],  marker='|', linestyle='None', color=c,
                          markersize=10, markeredgewidth=1.5)
    handles.append(vertical_line)

plt.legend(handles, labels)

EDIT (Using axvline instead of plot)

for x, c in zip(vertical_pos, colors):
    ax_ = plt.axvline( x=x, linestyle='-', color=c, label='Vertical x=%s' %x)

_, labels = ax.get_legend_handles_labels()

for c in colors:
    vertical_line = lines.Line2D([], [],  marker='|', linestyle='None', color=c,
                          markersize=10, markeredgewidth=1.5)
    handles.append(vertical_line)

plt.legend(handles, labels)

enter image description here

Upvotes: 4

Related Questions