Matplotlib : Making A Colored Markers Legend From Scratch
In Matplotlib, i'm trying to make a legend with colored 'markers' like this one : this one has been made using the scatter function, but is not adapted to my plot. I'd like to pro
Solution 1:
Following the example given in the legend guide, you can use a Line2D
object instead of a marker
object.
The only difference to the example given in the guide is you want to set linestyle='None'
import matplotlib.linesas mlines
import matplotlib.pyplotas plt
blue_star = mlines.Line2D([], [], color='blue', marker='*', linestyle='None',
markersize=10, label='Blue stars')
red_square = mlines.Line2D([], [], color='red', marker='s', linestyle='None',
markersize=10, label='Red squares')
purple_triangle = mlines.Line2D([], [], color='purple', marker='^', linestyle='None',
markersize=10, label='Purple triangles')
plt.legend(handles=[blue_star, red_square, purple_triangle])
plt.show()
Solution 2:
You could subclass the HandlerBase
to create a handler from a tuple of (color, marker)
.
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerBase
list_color = ["c", "gold", "crimson"]
list_mak = ["d","s","o"]
list_lab = ['Marker 1','Marker 2','Marker 3']
ax = plt.gca()
classMarkerHandler(HandlerBase):
defcreate_artists(self, legend, tup,xdescent, ydescent,
width, height, fontsize,trans):
return [plt.Line2D([width/2], [height/2.],ls="",
marker=tup[1],color=tup[0], transform=trans)]
ax.legend(list(zip(list_color,list_mak)), list_lab,
handler_map={tuple:MarkerHandler()})
plt.show()
Post a Comment for "Matplotlib : Making A Colored Markers Legend From Scratch"