Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

python - Matplotlib : making a colored markers legend from scratch

In Matplotlib, i'm trying to make a legend with colored "markers" like this one :

Markers legend

this one has been made using the scatter function, but is not adapted to my plot. I'd like to produce a legend "from scratch", without associated data. The color is important, and therefore should be an attribute of each marker.

I've tried

import matplotlib.markers as mmark
list_mak = [mmark.MarkerStyle('.'),mmark.MarkerStyle(','),mmark.MarkerStyle('o')]
list_lab = ['Marker 1','Marker 2','Marker 3']

plt.legend(list_mak,list_lab)

But :

1) The MarkerStyle class doesn't support color information

2) I get the warning :

UserWarning: Legend does not support <matplotlib.markers.MarkerStyle object at 0x7fca640c44d0> instances.
A proxy artist may be used instead.

But how can I define a proxy artist based on a marker ?

Thanks for your help !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.lines as mlines
import matplotlib.pyplot as 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()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...