Help Legend Matplotlib

I am writing a script that line up multiple points. I am also trying to create a legend from these points. To summarize the script, I draw a few "types" of points (name them "a", "b", "c"). These points have different colors and shapes: 'a' - 'go' 'b' - 'rh' 'c' - 'k ^'.

This is a shortened version of the relevant parts of my script:

lbl = #the type of point x,y is (a,b,c)
for x,y in coords:
   if lbl in LABELS:
      plot(x, y, color)
   else:
      LABELS.add(lbl)
      plot(x, y, color, label=lbl)
 legend()

What I'm doing here is just to draw a bunch of dots and label them. However, I found out if I add a label to each point, then the legend will contain an entry for each point. I need only one entry for each type of point (a, b, c). So, I changed my script to look like this. Is there a better way to do this? If I have a million different types of points, then the LABELS data structure (set) will take up a lot of space.

+3
source share
1 answer

Group xand yaccording to the type of point. Select all points of the same type with one call plot:

import pylab
import numpy as np

lbl=np.array(('a','b','c','c','b','a','b','c','a','c'))
x=np.random.random(10)
y=np.random.random(10)
for t,color in zip(('a','b','c'),('go','rh','k^')):
    pylab.plot(x[lbl==t],y[lbl==t],color,label=t)
pylab.legend()
pylab.show()

alt text

+2
source

Source: https://habr.com/ru/post/1755823/


All Articles