user2820579
user2820579

Reputation: 3451

Change marker in the legend in matplotlib

Suppose that you plot a set of data:

plt.plot(x,y, marker='.', label='something')
plt.legend()

On the display, you will obtain . something, but how do you do to change it to - something, so that the marker that appears in the legend is a line a not a dot?

Upvotes: 12

Views: 15614

Answers (3)

msch
msch

Reputation: 1396

It works for 3d plots slightly differently:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

ax = plt.gca()
handles, labels =  ax.get_legend_handles_labels()
updated_handles = []

for handle in handles:              
   updated_handles.append(mpatches.Patch(                                  
   color=handle.get_markerfacecolor(),                                 
   label=handle.get_label()))
                     
by_label = dict(sorted(dict(zip(labels,
                updated_handles)).items()))
                            
ax.legend(by_label.values(), by_label.keys())

Upvotes: 0

user12259798
user12259798

Reputation:

To follow up with more info. If you want to make your marker in the legend more visible when using plt.scatter(), you can do the following to automate the marker change process.

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

handles, labels, plt.gca().get_legend_handles_labels()
updated_handles = []
for handle in handles:
  updated_handles.append(mpatches.Patch(color=handle.get_facecolor(), label=handle.get_label()))
by_label = dict(sorted(dict(zip(all_labels, updated_handles)).items()))
plt.figlegend(by_label.values(), by_label.keys(), ...)

If you would like to use a specific axis, change plt.gca() with yours. Also, on line 8 I sorted the legend, which is something you can choose not to do.

Upvotes: 0

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339695

The solution surely depends on the criterion by which you want to transform the marker. Doing this manually is straight forward:

import matplotlib.pyplot as plt

line, = plt.plot([1,3,2], marker='o', label='something')
plt.legend(handles = [plt.plot([],ls="-", color=line.get_color())[0]],
           labels=[line.get_label()])

plt.show()

enter image description here

Doing the same in an automated way, i.e. each line in the plot gets its corresponding legend handle, which is a line in the same color, but without markers:

import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D

plt.plot([1,3,2], marker='o', label='something')
plt.plot([2,3,3], marker='o', label='something else')

def update_prop(handle, orig):
    handle.update_from(orig)
    handle.set_marker("")

plt.legend(handler_map={plt.Line2D:HandlerLine2D(update_func=update_prop)})

plt.show()

enter image description here

Upvotes: 11

Related Questions