python - Matplotlib scatter plot with legend -


i want create matplotlib scatter plot, legend showing colour each class. example, have list of x , y values, , list of classes values. each element in x, y , classes lists corresponds 1 point in plot. want each class have own colour, have coded, want classes displayed in legend. paramaters pass legend() function achieve this?

here code far:

x = [1, 3, 4, 6, 7, 9] y = [0, 0, 5, 8, 8, 8] classes = ['a', 'a', 'b', 'c', 'c', 'c'] colours = ['r', 'r', 'b', 'g', 'g', 'g'] plt.scatter(x, y, c=colours) 

first, have feeling meant use apostrophes, not backticks when declaring colours.

for legend need shapes classes. example, following creates list of rectangles called recs each colour in class_colours.

import matplotlib.patches mpatches  classes = ['a','b','c'] class_colours = ['r','b','g'] recs = [] in range(0,len(class_colours)):     recs.append(mpatches.rectangle((0,0),1,1,fc=class_colours[i])) plt.legend(recs,classes,loc=4) 

output first code block

you use circles if wanted, check out matplotlib.patches documentation. there second way of creating legend, in specify "label" set of points using separate scatter command each set. example of given below.

classes = ['a','a','b','c','c','c'] colours = ['r','r','b','g','g','g'] (i,cla) in enumerate(set(classes)):     xc = [p (j,p) in enumerate(x) if classes[j]==cla]     yc = [p (j,p) in enumerate(y) if classes[j]==cla]     cols = [c (j,c) in enumerate(colours) if classes[j]==cla]     plt.scatter(xc,yc,c=cols,label=cla) plt.legend(loc=4) 

enter image description here

the first method 1 i've used, second found looking @ matplotlib documentation. since legends covering datapoints moved them, , locations legends can found here. if there's way make legend, wasn't able find after few quick searches in docs.


Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -