Create legend for scatter plot using sample label in matplotlib

I am using a scatter plot in matplotlib to plot some points. I have two 1D arrays, each holding the x and y coordinates of the samples. There is also another 1D array that stores the mark (to determine in what color the point should be drawn). I have programmed so far:

import matplotlib.pyplot as plt
X = [1,2,3,4,5,6,7]
Y = [1,2,3,4,5,6,7]
label = [0,1,4,2,3,1,1]
plt.scatter(X, Y, c= label, s=50)
plt.show()

      

Now I want to see what color the label matches? I was looking for an implementation of legends in matplotlib, like here: how to add a legend for scatter ()? However, they suggest creating a graph for each sample label. However, all my labels are in the same 1D array (label). How can I achieve this?

+3


source to share


1 answer


You can do this with a color card. Some examples on how to do this are here .

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
X = [1,2,3,4,5,6,7]
Y = [1,2,3,4,5,6,7]
label = [0,1,4,2,3,1,1]

# Define a colormap with the right number of colors
cmap = plt.cm.get_cmap('jet',max(label)-min(label)+1)

bounds = range(min(label),max(label)+2)
norm = colors.BoundaryNorm(bounds, cmap.N)

plt.scatter(X, Y, c= label, s=50, cmap=cmap, norm=norm)

# Add a colorbar. Move the ticks up by 0.5, so they are centred on the colour.
cb=plt.colorbar(ticks=np.array(label)+0.5)
cb.set_ticklabels(label)

plt.show()

      



You may have to play around to get the label labels with their colors, but you get the idea.

enter image description here

+2


source







All Articles